图形上下文

来源:互联网 发布:软件负载均衡技术 编辑:程序博客网 时间:2024/05/17 08:34

实现方式1:
- (void)drawRect:(CGRect)rect{
// 1.获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.拼接路径(绘图的信息)
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 125)];
[path addLineToPoint:CGPointMake(240, 125)];
// 3.路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
// 设置绘图的状态
[[UIColor redColor] set];
CGContextSetLineWidth(ctx, 10);
CGContextSetLineCap(ctx, kCGLineCapRound);
// 4.渲染
CGContextStrokePath(ctx);

// 第二根线(需要再拼接路径,否则因为是一条路径会出现另一种吓尿了的效果)UIBezierPath *path1 = [UIBezierPath bezierPath];[path1 moveToPoint:CGPointMake(125, 10)];[path1 addLineToPoint:CGPointMake(125, 240)];CGContextAddPath(ctx, path1.CGPath);// 4.渲染(分开渲染,否则颜色等状态无法分别设置)CGContextStrokePath(ctx);

}

实现方式2:
- (void)drawRect:(CGRect)rect{
// 1.获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.把ctx拷贝一份放在栈中
CGContextSaveGState(ctx);
// 3.拼接路径(绘图的信息)
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10, 125)];
[path addLineToPoint:CGPointMake(240, 125)];
// 4.路径添加到上下文
CGContextAddPath(ctx, path.CGPath);
// 设置绘图的状态
[[UIColor redColor] set];
CGContextSetLineWidth(ctx, 10);
CGContextSetLineCap(ctx, kCGLineCapRound);
// 5.渲染
CGContextStrokePath(ctx);
// 第二根线
UIBezierPath *path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointMake(125, 10)];
[path1 addLineToPoint:CGPointMake(125, 240)];
CGContextAddPath(ctx, path1.CGPath);
// 6. 把栈顶上下文取出来,替换当前上下文
CGContextRestoreGState(ctx);
// 7.渲染
CGContextStrokePath(ctx);
}

0 0
原创粉丝点击