图形上下文

实现方式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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值