做需求的时候,发现有需要给图片水印添加背景颜色的,搜了好久,没有找到需要的例子,试了下通过view去调用drawInRect方法行不通,自己摸索下用画布填充的方式ok了,记录一下。
UIImage *imageAddBgText(UIImage *img, NSString *mark) {
UIImage *newImage = [MTImageCompressHelper imageCompressForWidth:img targetWidth:720];
int imgWidth = newImage.size.width;
int imgHeight = newImage.size.height;
UIGraphicsBeginImageContext(newImage.size);
[[UIColor redColor] set];
[newImage drawInRect:CGRectMake(0, 0, imgWidth, imgHeight)];
CGFloat textH = heightForString(mark, 24, imgWidth, 0);
CGRect bgFrame = CGRectMake(0, imgHeight-textH-20, imgWidth, textH+20);
CGRect markFrame = CGRectMake(10, imgHeight-textH-10, imgWidth-20, textH);
//画布填充方法begin
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, UIColor.whiteColor.CGColor);
CGContextFillRect(context, bgFrame);
//画布填充方法 end
[mark drawInRect:markFrame withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24],NSForegroundColorAttributeName:[UIColor redColor]}];
UIImage *imageRet = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageRet = [MTImageCompressHelper compressedImageToLimitSizeOfKB:300 image:imageRet];
return imageRet;
}
网友评论