- 通过CAShapeLayer 比较高级的方法
我自定义一个DefrenceShapeView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.maskLayer = [CAShapeLayer layer];
_maskLayer.frame = self.bounds;
_maskLayer.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1);
_maskLayer.contentsScale = [UIScreen mainScreen].scale;
#if 1
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
_maskLayer.path = path.CGPath;
#else
//这里除了用path 来绘制图形也可以用 不规则的图片绘制
_maskLayer.contents = (id)[UIImage imageNamed:@"popo"].CGImage;
#endif
self.contentLayer = [CALayer layer];
_contentLayer.backgroundColor = [UIColor grayColor].CGColor;
_contentLayer.frame = self.bounds;
_contentLayer.mask = self.maskLayer;
[self.layer addSublayer:_contentLayer];
_contentLayer.masksToBounds = YES;
}
return self;
}
在vc 中用到的时候 :
DefrenceShapeView * shapeView = [[DefrenceShapeView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
shapeView.contentLayer.contents = (id)[UIImage imageNamed:@"123"].CGImage;
[self.view addSubview:shapeView];
- DarwRect 底层绘图
// 绘制一个小气泡
- (void)drawRect:(CGRect)rect {
CGFloat radius = 20;
CGFloat twoValueDefrence = 20;
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//创建path
CGMutablePathRef path = CGPathCreateMutable();
//画路径
CGPathMoveToPoint(path, NULL, 0, 0); // 开始的第一个点
/**
* void CGPathAddArcToPoint(
CGMutablePathRef __nullable path,
const CGAffineTransform * __nullable m,
CGFloat x1, CGFloat y1, //这个是当前的点
CGFloat x2, CGFloat y2, //这个是另外一个点。通过这两个点 和 半径来确定 一个弧形
CGFloat radius)
*/
CGPathAddArcToPoint(path, NULL, rect.size.width, 0, rect.size.width, rect.size.height, radius);
CGPathAddArcToPoint(path, NULL, rect.size.width, rect.size.height, twoValueDefrence, rect.size.height, radius);
CGPathAddArcToPoint(path, NULL,twoValueDefrence, rect.size.height,twoValueDefrence, twoValueDefrence, radius);
CGPathAddArcToPoint(path, NULL, twoValueDefrence, twoValueDefrence, 0, 0, radius);
//CGPathAddLineToPoint(path, NULL, twoValueDefrence, twoValueDefrence);
CGPathAddLineToPoint(path, NULL, 0, 0);
//所有的点都加好了,然后把path 加入到contextRef 中来
CGContextAddPath(contextRef, path);
//绘制路径
[[UIColor blueColor]setStroke];
[[UIColor lightGrayColor]setFill];
//执行绘制
CGContextDrawPath(contextRef, kCGPathFillStroke);
CGPathRelease(path);
}