您的位置:首页 > 其它

简单绘制图形

2015-04-23 13:56 92 查看
1.使用Core Graphics绘制

CGContextRef context = UIGraphicsGetCurrentContext();

绘图前设置:

CGContextSetRGBFillColor/CGContextSetFillColorWithColor //填充色
CGContextSetRGBStrokeColor/CGContextSetStrokeColorWithColor //笔颜色
CGContextSetLineWidth //线宽度
绘图后设置:

CGContextDrawPath

注: 画完图后,先用CGContextStrokePath来描线,后用CGContextFillPath来填充形状内的颜色.

2.常见图形绘制:

CGContextFillRect/CGContextFillRects
CGContextFillEllipseInRect
CGContextAddRect/CGContextAddRects//矩形
CGContextAddEllipseInRect//椭圆
CGContextAddQuadCurveToPoint//二次曲线
CGContextAddArcToPoint//曲线
CGContextMoveToPoint//开始点
CGContextAddLineToPoint
CGContextAddLines
CGContextClosePath//几条线连起来


例如画一个三角形

CGPoint sPoints[3];//坐标点
sPoints[0] =CGPointMake(100, 220);//坐标1
sPoints[1] =CGPointMake(130, 220);//坐标2
sPoints[2] =CGPointMake(130, 160);//坐标3
CGContextAddLines(context, sPoints, 3);//添加线
CGContextClosePath(context);//三条线连起来
CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径


2 使用UIBezierPath对象

UIBezierPath的使用相当简单,分为三步:
* 创建path
* 添加路径到path
* 将path绘制出来

例如我们来画条线:

UIBezierPath *path = [UIBezierPath bezierPath];
// 添加路径[1条点(100,100)到点(200,100)的线段]到path
[path moveToPoint:CGPointMake(100 , 100)];
[path addLineToPoint:CGPointMake(200, 100)];

// 将path绘制出来
[path stroke];

同样的我们也可以画一个圆

startAngle为开始的弧度,endAngle为 结束的弧度,clockwise 0为顺时针,1为逆时针

UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:self.center radius:100.0 startAngle:0.0 endAngle:180.0 clockwise:YES];
[path stroke];

UIBezierPath颜色的设置并没有包含在自己类中,而是通过UIColor直接设置的。
例:

// 设置描边色
[[UIColor blueColor] setStroke];
// 设置填充色
[[UIColor redColor] setFill];

看上去是UIColor的方法,其实也是对于CGContextRef的渲染,最终还是作用到CGConextRef上的
UIBezierPath其实也就是对CGPathRef的封装

所以UIBezierPath通过UIColor的方法来设置颜色也就不奇怪了。

因为UIColor和UIBezierPath最终还是通过Core Graphics的方法来绘图的,只不过苹果又封装了一层OC。

UIBezierPath类包括bezierPathWithRect: and bezierPathWithOvalInRect:方法去创建椭圆或者矩形形状的path
addQuadCurveToPoint:controlPoint:二次曲线
addCurveToPoint:controlPoint1:controlPoint2:三次曲线
在调用上面两个方法之前要设置当前点。当曲线完成之后,current点会被更新为指定的end point。


例子:

绘制两个椭圆

- (void)drawRect:(CGRect)rect {

CGMutablePathRef cgPath = CGPathCreateMutable();

CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(0, 0, 300, 300));

CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(50, 50, 200, 200));

UIBezierPath* aPath = [UIBezierPath bezierPath];

aPath.CGPath = cgPath;

aPath.usesEvenOddFillRule = YES;

CGPathRelease(cgPath);

// 将path绘制出来

[[UIColor blueColor] setStroke];

[aPath stroke];

}


UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:

CGRectMake(0, 0, 200, 100)];

//创建的path相对于原点(0,0)

// Set the render colors

[[UIColor blackColor] setStroke];

[[UIColor redColor] setFill];

CGContextRef aRef = UIGraphicsGetCurrentContext();

CGContextSaveGState(aRef);

//移到(50,50)的位置

CGContextTranslateCTM(aRef, 50, 50);

aPath.lineWidth = 5;

[aPath fill];

[aPath stroke];

CGContextRestoreGState(aRef);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: