图片拉伸 mask绘制,渐变色背景
@implementation TCPostContentBackGroundView
-(instancetype)init{
if (self = [super init]){
self.gradientType = TCLinearGradientTypeFromLeftTopToRightBottom;
self.locations = @[@0, @1];
self.tc_cornerRadius = 10;
self.colors = @[[UIColor tc_colorWithHex:0xF1F1F1], [UIColor tc_colorWithHex:0xF1F1F1]];
}
return self;
}
//主线程绘制
-(void)addMasklayer{
if (self.typeGradientView == kTCLinearGradientViewTypeAI) {
self.colors = @[[UIColor tc_colorWithHex:0xF7F0FF alpha:0.65],[UIColor tc_colorWithHex:0xE7F1FF alpha:0.65] ];
}else{
self.colors = @[[UIColor tc_colorWithHex:0xF1F1F1], [UIColor tc_colorWithHex:0xF1F1F1]];
}
//绘制时候宽高不能为0
if (self.size.width == 0 ||
self.size.height == 0) {
return;
}
//已设置图片的slicing
UIImage *imageOriginal = [UIImage imageNamed:@"tc_postContentBG"];
UIImage* newImage = [self generateImageFromImageViewWith:imageOriginal];
CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (id)[newImage CGImage];;
maskLayer.frame = CGRectMake(0, 0, newImage.size.width, newImage.size.height);
self.layer.mask = maskLayer;
[self layoutIfNeeded];
}
- (UIImage *)generateImageFromImageViewWith:(UIImage* )originalImage {
CGSize targetSize = self.bounds.size;
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);
[originalImage drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
UIImage *stretchedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return stretchedImage;
}