1.简单地添加一个layer视图
self.movableCircleLayer = [CALayer layer]; /// 指定大小 self.movableCircleLayer.bounds = CGRectMake(0, 0, kLayerWidth, kLayerWidth); /// 指定中心点 self.movableCircleLayer.position = CGPointMake(self.view.center.x, 100); /// 圆形 self.movableCircleLayer.cornerRadius = kLayerWidth / 2; /// 背景色 self.movableCircleLayer.backgroundColor = [UIColor greenColor].CGColor; /// 设置阴影 self.movableCircleLayer.shadowColor = [UIColor grayColor].CGColor; self.movableCircleLayer.shadowOffset = CGSizeMake(3, 3); self.movableCircleLayer.shadowOpacity = 0.8; [self.view.layer addSublayer:self.movableCircleLayer];
2,使用图层添加一张图片
/// 图层上添加图片 -(void)drawImageWithContent{ CALayer * layer = [CALayer layer]; layer.bounds = CGRectMake(0,0,kPhotoWidth,kPhotoWidth); layer.position = self.view.center; layer.cornerRadius = kPhotoWidth / 2; layer.masksToBounds = YES; layer.borderColor = [UIColor whiteColor].CGColor; layer.borderWidth = 1; // 如果只是显示图片,不做其它处理,直接设置contents就可以了,也就不会出现 // 绘图和图像倒立的问题了 layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"hahaha.jpg"].CGImage); [self.view.layer addSublayer:layer]; }
3、使用图层代理添加一个有阴影的图片
/// 通过层代理绘制图片 -(void)drawImage{ CALayer * layer = [CALayer layer]; layer.bounds = CGRectMake(0, 0, kPhotoWidth, kPhotoWidth); layer.position = CGPointMake(self.view.center.x, self.view.bounds.size.height-100); layer.cornerRadius = kPhotoWidth/2; layer.masksToBounds = YES; layer.borderColor = [UIColor whiteColor].CGColor; layer.borderWidth = 1; layer.delegate = self; /// 添加到父视图图层上 [self.view.layer addSublayer:layer]; // 当设置masksToBounds为YES后,要想要阴影效果,就需要额外添加一个图层作为阴影图层了 CALayer * subLayer = [CALayer layer]; subLayer.position = layer.position; subLayer.bounds = layer.bounds; subLayer.cornerRadius = layer.cornerRadius; subLayer.shadowOpacity = 1.0; subLayer.shadowColor = [UIColor redColor].CGColor; subLayer.shadowOffset = CGSizeMake(2, 1); subLayer.borderWidth = layer.borderWidth; subLayer.borderColor = [UIColor whiteColor].CGColor; [self.view.layer insertSublayer:subLayer above:layer]; /// 调用此方法,否则代理不会调用 [layer setNeedsDisplay]; } /// 代理方法 -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { /// 将当前上下文入zhan CGContextSaveGState(ctx); // 注意:坐标系统与UIView的不同,这里使用的是笛卡尔积坐标系,也就是左下角为(0,0) // 所以,我们只要记住这点就可以很容易地变换了。 // 处理图片倒立的问题 // 默认呈现是倒立的,因此需要将形变矩阵的sy设置为-1就成了正立的了 // 先缩放后平移也可以 CGContextScaleCTM(ctx, 1, -1); CGContextTranslateCTM(ctx, 0, -kPhotoWidth); // /// 平移后水平旋转 // // CGContextTranslateCTM(ctx, kPhotoWidth, kPhotoWidth); // CGContextRotateCTM(ctx, 3.1415926 / 180 *180); UIImage * imgage = [UIImage imageNamed:@"hahaha.jpg"]; CGContextDrawImage(ctx, CGRectMake(0, 0, kPhotoWidth, kPhotoWidth), imgage.CGImage); /// 任务已完成,将上下文退栈 CGContextRestoreGState(ctx); }
时间: 2024-10-23 22:04:55