通过CAShapeLayer 和 DrawRect 来画图形

本文介绍如何使用 CAShapeLayer 在 iOS 开发中实现自定义视图 DefrenceShapeView,包括通过路径和图片设置遮罩效果,并提供了一个绘制小气泡的 drawRect 方法示例。
  1. 通过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];
  1. 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);


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值