标签:
在CALayer上绘图:
//创建子层(使用默认的锚点) CALayer *subLayer = [[CALayer alloc]init]; subLayer.bounds = CGRectMake(0,0,100, 100); subLayer.position = self.view.center; subLayer.backgroundColor = [[UIColor redColor]CGColor];
//设置圆角半径,设置为50,此时的子层为圆形 subLayer.cornerRadius = 50; [self.view.layer addSublayer:subLayer];
//设置层的代理 subLayer.delegate = self;
//只有发送setNeedsDisplay这个消息时才会调用代理方法 [subLayer setNeedsDisplay];
#pragma mark -CALayer的代理方法 -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { //画矩形 CGContextAddRect(ctx, CGRectMake(0, 0, 50, 50));
//设置颜色 CGFloat components[4] = {0.0,1.0,0.0,1.0}; CGContextSetStrokeColor(ctx, components);
//这种方式也可以设置颜色 //CGContextSetStrokeColorWithColor(ctx,[[UIColor greenColor]CGColor]);
//旋转坐标系 CGContextScaleCTM(ctx, 1, -1); CGContextTranslateCTM(ctx, 0, -100); //画笑脸图像 UIImage *image = [UIImage imageNamed:@"1.png"]; CGContextDrawImage(ctx, CGRectMake(0, 0, 100, 100), [image CGImage]); //画路径 CGContextDrawPath(ctx, kCGPathStroke); }
#import "ViewController.h" #import "MyLayer.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //创建子层 MyLayer *myLayer = [[MyLayer alloc]init]; myLayer.bounds = CGRectMake(0, 0, 100, 100); myLayer.position = CGPointMake(100, 100);
//设置子层背景色为灰色 myLayer.backgroundColor = [[UIColor grayColor]CGColor]; [self.view.layer addSublayer:myLayer]; [myLayer setNeedsDisplay]; } @end
#import "MyLayer.h" #import <UIKit/UIKit.h> @implementation MyLayer //重写这个方法 -(void)drawInContext:(CGContextRef)ctx { //绘制矩形 CGContextAddRect(ctx, CGRectMake(0, 0, 50, 50)); //第一种设置颜色方式: //设置颜色空间(选择配色方案:RGB,红、绿、蓝) CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); CGContextSetStrokeColorSpace(ctx, colorspace);
//数组中四个内容:前三个分别为红绿蓝颜色值,后一个为透明度 CGFloat components[4] = {0.0,1.0,0.0,1.0}; CGContextSetStrokeColor(ctx, components); //这是另一种比较简单的设置颜色的方式 //CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor]CGColor]); //绘制描边路径 CGContextDrawPath(ctx, kCGPathStroke); //释放create出的属性,防止内存泄露 CGColorSpaceRelease(colorspace); } @end
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/4883127.html