直接上图,效果如图1.0
网上找了几个都不是很合适,于是自己硬着头皮写了一个,分享出来,希望可以帮助到同样需求的人,话不多少 ,直接上代码
// IrregularLabel.m
// Created by yang.sun on 2018/4/4.
// Copyright © 2018年 yang.sun. All rights reserved.
/*****
若label的长是宽的2倍 则三角形为直角,旋转可 做为 边角标签
self.transform = CGAffineTransformMakeRotation(M_PI_4);
*/
#import "IrregularLabel.h"
@interface IrregularLabel ()
/** 遮罩 */
@property (nonatomic, strong) CAShapeLayer *maskLayer;
/** 路径 */
@property (nonatomic, strong) UIBezierPath *borderPath;
@end
@implementation IrregularLabel
- (instancetype)initWithFrame:(CGRect)frame {
if(self= [superinitWithFrame:frame]) {
// 初始化遮罩
self.maskLayer = [CAShapeLayer layer];
// 设置遮罩
[self.layersetMask:self.maskLayer];
// 初始化路径
self.borderPath = [UIBezierPath bezierPath];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
// 遮罩层frame
self.maskLayer.frame = self.bounds;
// 设置path起点
[self.borderPath moveToPoint:CGPointMake(self.bounds.size.height, 0)];
//添加路线
[self.borderPath addLineToPoint:CGPointMake(0,self.bounds.size.height)];
[self.borderPath addLineToPoint:CGPointMake(self.bounds.size.width,self.bounds.size.height)];
//关闭path
[self.borderPath closePath];
//三角形内填充颜色
// 暂时无效不知为何
// [[UIColor redColor] setFill];
// [self.borderPath fill];
// 将这个path赋值给maskLayer的path
self.maskLayer.path = self.borderPath.CGPath;
}
@end