快速地通过UIImage添加文本-以编程方式

问题描述

我正在尝试通过UIView添加文本,就像在instagram Stories上一样。 我正在使用此功能,在屏幕尺寸大小的视图上绘制textViews

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,y: textView.frame.minY,width: textView.frame.width,height: textView.frame.height)
        

        textView.text.draw(in: rect,withAttributes: textFontAttributes as [NSAttributedString.Key : Any])

    }
    
    let newImage = UIGraphicsGetimageFromCurrentimageContext()
    
    UIGraphicsEndImageContext()
    
    return newImage!
}

已绘制文本,问题在于文本视图不在viewPassed中的确切位置。特别是,相对于原始textView而言,所绘制的文本在左上方。

我想知道为什么会发生这种情况以及如何解决它,我想尽办法,但似乎找不到解决方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)