问题描述
我有一台照相机,可以为UIImage提供1920x1080的分辨率,我实现了一个系统,可以在其中添加UITextViews作为子视图,我的目标是将它们添加到原始UIImage并导出分辨率为1920x1080的最终图像。
所以我一直在想的过程是这样的:
-
我在view.frame上添加了upperView,负责绘制屏幕上存在的所有textView。
-
然后我要在原始UIImage上按比例缩放此视图
这是我为执行此操作而实现的代码:
func passingAndDrawingTextViews(textViews : [UITextView],viewPassed : UIView,inImage : UIImage) -> UIImage{
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(viewPassed.frame.size,false,scale)
viewPassed.draw(CGRect(x: 0,y: 0,width: viewPassed.frame.width,height: viewPassed.frame.height))
//adding each textView
textViews.forEach { (textView) in
let textColor = textView.textColor
let textFont = UIFont(name: textView.font!.fontName,size: textView.font!.pointSize)
let textAlignment = textView.textAlignment
//alignment of the text
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let textFontAttributes = [
NSAttributedString.Key.font: textFont,NSAttributedString.Key.foregroundColor: textColor,NSAttributedString.Key.paragraphStyle : paragraphStyle,]
let rect = CGRect(x: textView.frame.minX + textView.textContainer.lineFragmentPadding,y: textView.frame.minY + textView.textContainerInset.top,width: textView.frame.width,height: textView.frame.height)
textView.text.draw(in: rect,withAttributes: textFontAttributes as [NSAttributedString.Key : Any])
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(inImage.size)
let rect = CGRect(x: 0,width: inImage.size.width,height: inImage.size.height)
inImage.draw(in: CGRect(x: 0,height: inImage.size.height))
newImage!.draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
在函数中,我分别传递textViews,upperView和originalImage的列表。
但是问题是我得到的textView在x轴上拉伸了。我不知道为什么会这样。
我得到的:
我想要的
解决方法
您要在此行中传递的矩形:
newImage!.draw(in: rect)
实际是屏幕本身的大小,因此图像将拉伸以填充该矩形。 所以做这个:
let rect = CGRect(x: 0,y: 0,width: inImage.size.width,height: inImage.size.height)
您要传递的图像的大小。