实现类似QQ消息图片那种遮罩层
上图
1、CALayer 、 CAShapeLayer
什么是CALayer? CALayer(这里简单地称其为层)。 首先要说的是CALayers 是屏幕上的一个具有可见内容的矩形区域,每个UIView都有一个根CALayer
其子类,如CAGradientLayer,CATextLayer, CAShapeLayer等等
2 、CAShapeLayer
CAShapeLayer 是继承与clayer的一个类,是quare2d中对图层操作最基本的一个类的扩展,通过CAShapeLayer 我们可以画出我们需要的各种图形,和UIBezierPath结合时,进行各种绘制
使用UIBezierPath绘制五角形
Swift
func Pentagon() {
maskLayer = CAShapeLayer()
let path = UIBezierPath()
path.moveToPoint(CGPointMake(50.0, 2.0))
path.addLineToPoint(CGPointMake(84.0, 86.0))
path.addLineToPoint(CGPointMake(6.0, 33.0))
path.addLineToPoint(CGPointMake(96.0, 33.0))
path.addLineToPoint(CGPointMake(17.0, 86.0))
path.closePath()
maskLayer?.path = path.CGPath
maskLayer?.fillColor = UIColor.blackColor().CGColor
maskLayer?.strokeColor = UIColor.redColor().CGColor
maskLayer?.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1)
maskLayer?.contentsScale = UIScreen.mainScreen().scale
maskLayer!.frame = self.bounds
contentLayer = CALayer()
contentLayer!.mask = maskLayer
contentLayer!.frame = self.bounds
self.layer.addSublayer(contentLayer!)
}
OC
- (void)Pentagon
{
_maskLayer = [CAShapeLayer layer];
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 50.0, 2.0);
CGPathAddLineToPoint(path, NULL, 84, 86);
CGPathAddLineToPoint(path, NULL, 6.0, 33.0);
CGPathAddLineToPoint(path, NULL, 96.0, 33.0);
CGPathAddLineToPoint(path, NULL, 17.0, 86.0);
CGPathAddLineToPoint(path, NULL, 50.0, 2.0);
_maskLayer.path = path;
_maskLayer.fillColor = [UIColor blackColor].CGColor;
_maskLayer.strokeColor = [UIColor redColor].CGColor;
_maskLayer.frame = self.bounds;
_maskLayer.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1);
_maskLayer.contentsScale = [UIScreen mainScreen].scale; //非常关键设置自动拉伸的效果且不变形
_contentLayer = [CALayer layer];
_contentLayer.mask = _maskLayer;
_contentLayer.frame = self.bounds;
[self.layer addSublayer:_contentLayer];
}
使用Image创建遮罩层
1.1) 需要一个image图片(我们就是需要这种形状的遮罩层)
1.3)代码
Swift
class customShapeImageView: UIImageView {
var maskLayer : CAShapeLayer?
func Custom() {
maskLayer = CAShapeLayer()
maskLayer!.frame = self.bounds
maskLayer?.contentsScale = UIScreen.mainScreen().scale//像素尺寸和视图大小的比例 3.0
maskLayer?.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1)//可以用来定义全面拉伸的范围(http://www.kancloud.cn/manual/ios/97766)
maskLayer?.contents = UIImage.init(named: "communication_chat_right")?.CGImage
self.layer.mask = maskLayer
}
}
OC
- (void)PictureShape
{
_maskLayer = [CAShapeLayer layer];
_maskLayer.frame = self.bounds;
_maskLayer.contentsScale = [UIScreen mainScreen].scale;
_maskLayer.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1);
_maskLayer.contents = (id)[UIImage imageNamed:@"communication_chat_right.png"].CGImage;
[self.layer setMask:_maskLayer];
}
Demo
Demo中没有使用oc编辑的ImageView
Swift使用oc类请看Swift与OC混编_Swift使用OC