iOS 关于在图片上绘制文字导致图片失真的解决方案
程序员文章站
2022-03-21 13:56:00
...
由于业务需要, 图片需要更新文本, 而此图片又需要保存. 所以使用图片上绘制文字. (也就是UIview 转 UIImageView).
但是这种情况下, 在retain 高清屏显示的时候, 会出现图片像素降低, 失真的情况.
故而找了一下解决方案, 在此记录一下.
//图片添加文字
+ (UIImage )imageWithText:(NSString )text
textFont:(NSInteger)fontSize
textColor:(UIColor *)textColor
textFrame:(CGRect)textFrame
originImage:(UIImage *)image
imageLocationViewFrame:(CGRect)viewFrame {if (!text) { return image; } if (!fontSize) { fontSize = 15; } if (!textColor) { textColor = [UIColor blackColor]; } if (!image) { return nil; } if (viewFrame.size.height==0 || viewFrame.size.width==0 || textFrame.size.width==0 || textFrame.size.height==0 ){return nil;} NSString *mark = text; CGFloat height = [mark sizeWithPreferWidth:textFrame.size.width font:[UIFont systemFontOfSize:fontSize]].height; // CGFloat height
= [mark sizeWithPreferWidth:textFrame.size.width font:[UIFont fontWithName:@”huakanghaibao” size:fontSize]].height;
if ((height + textFrame.origin.y) > viewFrame.size.height) { // 文字高度超出父视图的宽度 height = viewFrame.size.height - textFrame.origin.y; } // CGFloat w = image.size.width; // CGFloat h = image.size.height; //这个函数是最初使用的, 导致图片失真. // UIGraphicsBeginImageContext(viewFrame.size); //替换这个解决图片失真 UIGraphicsBeginImageContextWithOptions(viewFrame.size, NO, [UIScreen mainScreen].scale); [image drawInRect:CGRectMake(0, 0, viewFrame.size.width, viewFrame.size.height)]; NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize], NSForegroundColorAttributeName : textColor
};
//位置显示
CGFloat tWidth = [self getWidthWithTitle:mark font:[UIFont systemFontOfSize:fontSize]];
CGFloat t1x = 0.0;
//文本位置
t1x = (image.size.width / 2) - (tWidth) / 2;[mark drawInRect:CGRectMake(/*textFrame.origin.x*/t1x, textFrame.origin.y, tWidth/*textFrame.size.width*/, height)
withAttributes:attr];
UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return aimg; }