视图根据drawRect: 方法将自己绘制到图层上。UIView的子类可以覆盖drawRect:方法,从而完成自定义的绘图任务.
覆盖drawRect:方法后首先应该获取视图从UIView继承而来的bounds属性,该属性定义了一个矩形范围,表示视图的绘制区域。
在这里要注意frame与bounds的不同,frame用于确定与视图层次结构中其他视图的相对位置,从而将自己的图层与其他视图的图层正确组合成屏幕上的图像。而bounds属性用于确定绘制区域。
-(void)drawRect:(CGRect)rect
{
CGRect bounds=self.bounds;
//开始根据bounds大小绘制图形
//这里可以使用UIBezierPath类
UIBezierPath *path=[[UIBezierPath alloc] init];
//绘制圆形,定义一个0到M_PI*2.0弧度的路径(整圆)
[path addArcWithCenter:(圆心位置)
radius:(半径)
startAngle:0.0
endAngle:M_PI*2.0
clockwise:YES];
//在最后需要调用绘制路径才能将圆形绘制在屏幕上
[path stroke];
}
UIBezierPath类还有一些属性和方法,如绘制的线的宽度lineWidth、移动点到某一位置的moveToPoint:方法、绘制直线addLineToPoint:方法等,这些可以参考API手册。
使用Core Graphics绘制阴影和渐变:
视图的 drawRect:方法在执行之前,系统首先为视图的图层创建一个图形上下文,然后为绘画状态设置一些默认参数。阴影和渐变的绘制就是通过获取图形上下文,然后设置基本方法来实现。
在drawRect:方法中获取图形上下文的办法是CGContextRef currentContext=UIGraphicsGetCurrentContext();
绘制阴影的代码
//获取图形上下文
CGContextRef currentContext=UIGraphicsGetCurrentContext();
//保存上下文
CGContextSaveGState(currentContext);
//设置阴影效果,第二个参数为阴影的偏移量,第三个参数为模糊指数
CGContextSetShadow(currentContext, CGSizeMake(4, 7), 3);
//绘制图片
UIImage *logoImage=[UIImage imageNamed:@"logo.png"];
[logoImage drawInRect:rect];
//恢复没有阴影效果
CGContextRestoreGState(currentContext);
这样绘制的图片就会带有阴影效果。
绘制渐变的代码:
UIBezierPath *mypath=[[UIBezierPath alloc]init];
//存储当前上下文
CGContextSaveGState(currentContext);
[mypath moveToPoint:CGPointMake(160, 142)];
[mypath addLineToPoint:CGPointMake(260, 446)];
[mypath addLineToPoint:CGPointMake(60, 446)];
[mypath addLineToPoint:CGPointMake(160, 142)];
[mypath stroke];
[mypath addClip];
//填充渐变
CGFloat locations[2]={0.0,1.0};
CGFloat components[8]={1.0,1.0,0.0,1.0,
0.0,1.0,0.0,1.0};
CGColorSpaceRef colorspace=CGColorSpaceCreateDeviceRGB();//获取色彩空间
/*指定渐变色
colorspace:颜色空间
components:颜色数组,注意由于指定了RGB颜色空间,那么四个数组元素表示一个颜色(red、green、blue、alpha),
如果有三个颜色则这个数组有4*3个元素
locations:颜色所在位置(范围0~1),这个数组的个数不小于components中存放颜色的个数
count:渐变个数,等于locations的个数
*/
CGGradientRef gradient=CGGradientCreateWithColorComponents(colorspace, components, locations, 2);
CGPoint startPoint=CGPointMake(160, 446);
CGPoint endPoint=CGPointMake(160,142);
/*绘制线性渐变
currentContext:图形上下文
gradient:渐变色
startPoint:起始位置
endPoint:终止位置
options:绘制方式,kCGGradientDrawsBeforeStartLocation 开始位置之前就进行绘制,到结束位置之后不再绘制,
kCGGradientDrawsAfterEndLocation开始位置之前不进行绘制,到结束点之后继续填充
*/
CGContextDrawLinearGradient(currentContext, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorspace);
CGContextRestoreGState(currentContext);