绘制圆角三角形的View

项目需要一个三角形的带毛玻璃效果的View这里写图片描述由于底部是用UIBlurEffect进行的虚拟化效果,所以这个三角形也需要自己绘制了,于是就开始各种找资料,爬文,参考了这个文章,和我开始的思路差不多,但是计算起来太麻烦了,后来想到一种方法,供大家参考

  • 自定义一个View,用来绘制三角形的View
  • 三角形的三个点为View的三个点
  • 设置transform,让View旋转45°
  • [self.view addSubview:[[SOView alloc] initWithFrame:CGRectMake(80, 140, 200, 200)]];
  • 这是自定义View中的代码
  • self.backgroundColor = [UIColor greenColor];
    CGMutablePathRef ref = CGPathCreateMutable();
    CGPathMoveToPoint(ref, NULL, 0 , 0);
    CGPathAddLineToPoint(ref, NULL, frame.size.width , 0);
    CGPathAddLineToPoint(ref, NULL, 0,frame.size.height);
    CGPathCloseSubpath(ref);

    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:ref];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = self.bounds;
    layer.path = path.CGPath;
    self.layer.mask = layer;

    self.layer.cornerRadius = 15;
    self.layer.masksToBounds = YES;
    self.transform =CGAffineTransformRotate(self.transform, M_PI_4);
    self.layer.mask = layer;

  • 效果 绘制圆角三角形的View_第1张图片
  • 这里可以看到虽然顶部已经圆角了,但是两个下角也是圆角了,并不是我们想要的,于是又以下修改
  • self.backgroundColor = [UIColor greenColor];
    CGMutablePathRef ref = CGPathCreateMutable();
    CGPathMoveToPoint(ref, NULL, 0 , 0);
    CGPathAddLineToPoint(ref, NULL, frame.size.width - 20 , 0);
    CGPathAddLineToPoint(ref, NULL, 0,frame.size.height - 20);
    CGPathCloseSubpath(ref);

    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:ref];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = self.bounds;
    layer.path = path.CGPath;
    self.layer.mask = layer;

    self.layer.cornerRadius = 15;
    self.layer.masksToBounds = YES;
    self.transform =CGAffineTransformRotate(self.transform, M_PI_4);
    self.layer.mask = layer;

  • 绘制圆角三角形的View_第2张图片

  • 这是效果,大体上符合我想要的了

  • UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *view = [[UIVisualEffectView alloc] init];
    view.frame = [UIScreen mainScreen].bounds;
    view.effect = effect;
    [self addSubview:view];

  • 添加模糊效果
  • 效果绘制圆角三角形的View_第3张图片
    *

如果文章有错误,还望指正,如果你有更好的实现方法,也希望我们可以多交流

你可能感兴趣的:(日常记录)