layerContant.delegate = self;
[layerContant setNeedsDisplay];
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
// 绘图
CGContextSaveGState(ctx);
// 图形上下文形变,避免图片倒立显示
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextTranslateCTM(ctx, 0.0, -150.0);
// 图片
UIImage *image = [UIImage imageNamed:@"header"];
CGContextDrawImage(ctx, CGRectMake(0.0, 0.0, 150.0, 150.0), image.CGImage);
CGContextRestoreGState(cox);
}
// 绘制实线、虚线
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
// 绘实线
// 线条宽
CGContextSetLineWidth(ctx, 1.0);
// 线条颜色
// CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
CGContextSetStrokeColorWithColor(ctx, [UIColor greenColor].CGColor);
// 方法1
// 坐标点数组
CGPoint aPoints[2];
aPoints[0] = CGPointMake(10.0, 50.0);
aPoints[1] = CGPointMake(140.0, 50.0);
// 添加线 points[]坐标数组,和count大小
CGContextAddLines(ctx, aPoints, 2);
// 根据坐标绘制路径
CGContextDrawPath(ctx, kCGPathStroke);
// 方法2
CGContextSetLineWidth(ctx, 5.0);
CGContextSetStrokeColorWithColor(ctx, [UIColor purpleColor].CGColor);
CGContextMoveToPoint(ctx, 10.0, 60.0); // 起点坐标
CGContextAddLineToPoint(ctx, 140.0, 60.0); // 终点坐标
CGContextStrokePath(ctx); // 绘制路径
// 绘虚线
// 线条宽
CGContextSetLineWidth(ctx, 2.0);
// 线条颜色
CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor);
// 虚线
CGFloat dashArray[] = {1, 1, 1, 1};
CGContextSetLineDash(ctx, 1, dashArray, 1);
// 起点
CGContextMoveToPoint(ctx, 10.0, 100.0);
// 终点
CGContextAddLineToPoint(ctx, 140.0, 100.0);
// 绘制路径
CGContextStrokePath(ctx);
}
// 内存管理,避免异常crash
- (void)dealloc
{
for (CALayer *layer in self.view.layer.sublayers)
{
if ([layer.delegate isEqual:self])
{
layer.delegate = nil;
}
}
NSLog(@"%@ 被释放了~", self);
}
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
注:相关教程知识阅读请移步到IOS开发频道。










