通过UIImage添加TextViews-Swift-以编程方式

问题描述

我有一台照相机,可以为UIImage提供1920x1080的分辨率,我实现了一个系统,可以在其中添加UITextViews作为子视图,我的目标是将它们添加到原始UIImage并导出分辨率为1920x1080的最终图像。

所以我一直在想的过程是这样的:

  1. 我在view.frame上添加了upperView,负责绘制屏幕上存在的所有textView。

  2. 然后我要在原始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轴上拉伸了。我不知道为什么会这样。

我得到的:

stretched

我想要的

not stretched

解决方法

您要在此行中传递的矩形:

newImage!.draw(in: rect)

实际是屏幕本身的大小,因此图像将拉伸以填充该矩形。 所以做这个:

let rect = CGRect(x: 0,y: 0,width: inImage.size.width,height: inImage.size.height)

您要传递的图像的大小。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...