微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决通过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)

您要传递的图像的大小。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。