最近有一個(gè)需求是要在圖片上加文字,第三方實(shí)現(xiàn)的很多,但是不想用SDK.打算用代碼自己寫(xiě).
最初的方案是自己在畫(huà)布上繪制,記錄用戶的旋轉(zhuǎn)角度和縮放倍數(shù),計(jì)算文字的位置,然后依次繪制到CGContext上.下邊是基本代碼.
但是這個(gè)實(shí)現(xiàn)方式有一個(gè)問(wèn)題就是位置需要精確計(jì)算.并且因?yàn)檫M(jìn)行了transform之后.UIView的frame整體值是有問(wèn)題的.x值不是左上角,而是最靠左側(cè)點(diǎn)的位置.y值為最靠上點(diǎn)的位置.導(dǎo)致整個(gè)坐標(biāo)系需要進(jìn)行計(jì)算.并且容易出錯(cuò).
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
//等比例縮放的話這里寬高都可以
CGFloat fltImageScale = self.imagePanle.image.size.width / self.imagePanle.width;
CGFloat fltTextScale = lblText.scale;
NSDictionary *dicAttribute = @{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont fontWithName:DP_FONTNAME size:17 * fltTextScale * fltImageScale],NSParagraphStyleAttributeName:paragraphStyle};
CGPoint textOrigin = [lblText convertPoint:CGPointZero toView:lblText.superview];
textOrigin = CGPointMake(textOrigin.x * fltImageScale, textOrigin.y * fltImageScale);
CGSize textSize = CGSizeMake(lblText.bounds.size.width * lblText.scale * fltImageScale, lblText.bounds.size.height * lblText.scale * fltImageScale);
CGRect textRect = CGRectMake(textOrigin.x, textOrigin.y, textSize.width, textSize.height);
//旋轉(zhuǎn)角度
CGFloat fltRotate = lblText.angle;
// [lblText.text drawInRect:textRect withAttributes:dicAttribute];
CGPoint translateOrignal =CGPointMake(textOrigin.x + textSize.width * 0.5,textOrigin.y + textSize.height * 0.5);
textOrigin = CGPointMake(-textSize.width * 0.5,-textSize.height * 0.5);
textRect.origin = CGPointMake(textOrigin.x, textOrigin.y);
CGContextTranslateCTM(context, translateOrignal.x,translateOrignal.y);
CGContextRotateCTM(context,radians(fltRotate));
[lblText.text drawInRect:textRect withAttributes:dicAttribute];
//復(fù)原
CGContextRotateCTM(context,radians(-fltRotate));
CGContextTranslateCTM(context, -translateOrignal.x,-translateOrignal.y);
最后的實(shí)現(xiàn)方式是在頁(yè)面上加了一個(gè)UIView,放置所有添加的UILable,在生成圖時(shí)選擇先繪制背景圖,然后將UIView生成一個(gè)圖片直接追加上去,不需要進(jìn)行位置的計(jì)算.唯一的一個(gè)需要注意的點(diǎn)就是CGContext的大小和位置問(wèn)題.我這里選擇使用image和它所在的UIImageView的縮放比例作為CGContext的scale使用.
CGFloat fltImageScale = self.image.size.width / self.imageView.bounds.size.width;
UIGraphicsBeginImageContextWithOptions(self.viewTextPanle.size, NO,fltImageScale);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.image drawInRect:self.viewTextPanle.bounds];
[self.viewTextPanle.layer renderInContext:context];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
while (self.viewTextPanle.subviews.firstObject) {
[self.viewTextPanle.subviews.firstObject removeFromSuperview];
}
self.imageView.image = resultImage;
有些功能實(shí)現(xiàn)起來(lái)很復(fù)雜.但是換一個(gè)思路其實(shí)特別簡(jiǎn)單,這里將自己的坑寫(xiě)出來(lái),希望能幫助到其他人