iOS在image上畫文字-畫圖片
阿新 • • 發佈:2018-11-02
專案想設定在圖片上新增圓形圖片,可獲取不到imageView,實在沒辦法就在圖片上畫上圖片
Demo:
// 在圖片上新增圖片;imageName 1.底部圖片名字imageName, image2 需新增的圖片 - (UIImage *)createShareImage:(UIImage *)tImage ContextImage:(UIImage *)image2 { UIImage *sourceImage = tImage; CGSize imageSize; //畫的背景 大小 imageSize = [sourceImage size]; UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); [sourceImage drawAtPoint:CGPointMake(0, 0)]; //獲得 圖形上下文 CGContextRef context=UIGraphicsGetCurrentContext(); //畫 自己想要畫的內容(新增的圖片) CGContextDrawPath(context, kCGPathStroke); CGRect rect = CGRectMake( imageSize.width/4,imageSize.height/5, imageSize.width/2, imageSize.height/2); CGContextAddEllipseInRect(context, rect); CGContextClip(context); [image2 drawInRect:rect]; //返回繪製的新圖形 UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
// 1.將文字新增到圖片上;imageName 圖片名字, text 需畫的字型 - (UIImage *)createShareImage:(UIImage *)tImage Context:(NSString *)text { UIImage *sourceImage = tImage; CGSize imageSize; //畫的背景 大小 imageSize = [sourceImage size]; UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); [sourceImage drawAtPoint:CGPointMake(0, 0)]; //獲得 圖形上下文 CGContextRef context=UIGraphicsGetCurrentContext(); CGContextDrawPath(context, kCGPathStroke); CGFloat nameFont = 8.f; //畫 自己想要畫的內容 NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:nameFont]}; CGRect sizeToFit = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, nameFont) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil]; NSLog(@"圖片: %f %f",imageSize.width,imageSize.height); NSLog(@"sizeToFit: %f %f",sizeToFit.size.width,sizeToFit.size.height); CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor); [text drawAtPoint:CGPointMake((imageSize.width-sizeToFit.size.width)/2,0) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:nameFont]}]; //返回繪製的新圖形 UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }