绘制原理
当一个应用程序绘制图像时,它首先会创建一个画布以供绘制。Cocoa把它称为图像的上下文。上下文定义了画布的大小和颜色信息的使用方式(例如,你可以有一个黑白画布,一个灰度画布等)。
一旦创建好上下文,就可以请求Cocoa开始绘制内容。
绘图的基本单元是路径。一个路径只是任意形状的名字。
构建路径时,需要指定路径的关键点。
在iOS上绘制阴影:
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef shadow = [UIColor redColor].CGColor;
CGSize shadowOffset = CGSizeMake(3, 3);
CGFloat shadowBlurRadius = 5;
CGRect pathRect = CGRectInset(self.bounds, 20, 20);
UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRect:pathRect];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow);
[[UIColor lightGrayColor] setFill];
[rectanglePath fill];
CGContextRestoreGState(context);
在iOS上绘制渐变
剪切当前图形上下文,然后从屏幕一个点到另一个点绘制渐变。
传递视图坐标空间中渐变开始和结束的坐标。
// 绘制渐变
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *gradientStartColor = [UIColor colorWithRed:0.0
green:0.2
blue:0.7
alpha:1];
UIColor *gradientEndColor = [UIColor colorWithRed:0.3
green:0.4
blue:0.7
alpha:1];
NSArray *gradientColors = @[(id)gradientStartColor.CGColor, (id)gradientEndColor.CGColor];
CGFloat gradientLocations[] = {0, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations);
CGRect pathRect = CGRectInset(self.bounds, 20, 20);
CGPoint topPoint = CGPointMake(self.bounds.size.width / 2, 20);
CGPoint bottomPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 20);
UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:4];
CGContextSaveGState(context);
[roundedRectanglePath addClip];
CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);