在UIimage上绘制文本时文本大小不同

时间:2016-02-15 10:07:22

标签: ios swift uiimage drawrect cgcontext

我正在处理项目,我需要在文本字段中添加文本。

但是当我看到图像上的文字时,它显示的字体大小小于文本字段的字体大小。

我使用以下方法在图像上绘制文字

func drawText(text: String, inImage image: UIImage, atPoint point: CGPoint, fontName:String, fontSize: String,textColor: UIColor) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(image.size, true, UIScreen.mainScreen().scale)
        UIGraphicsBeginImageContext(image.size)

        image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
        let rect: CGRect = CGRectMake(point.x, point.y, image.size.width, image.size.height)
        // UIColor.whiteColor().set()

        // set the font to Helvetica Neue 18
        if let sizeFont = NSNumberFormatter().numberFromString(fontSize) {

            // TODO: - Need to resolve issue
            let originalSize = sizeFont.integerValue

            let finalFontSize = CGFloat(originalSize)

            let fieldFont = UIFont(name: fontName, size:finalFontSize*1.5)

            // set the line spacing to 6
            let paraStyle = NSMutableParagraphStyle()
            // paraStyle.lineSpacing = 6.0

            // set the Obliqueness to 0.1
            // let skew = 0.1

            let attributes: NSDictionary = [
                NSForegroundColorAttributeName: textColor,
               // NSParagraphStyleAttributeName: paraStyle,
                // NSObliquenessAttributeName: skew,
                NSFontAttributeName: fieldFont!
            ]

            NSString(string: text).drawInRect(rect, withAttributes: attributes as? [String : AnyObject])

            let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }

        return nil
    }

字体大小可能是16-60px。

请告诉我可能的解决方案。

由于

2 个答案:

答案 0 :(得分:3)

你的代码似乎一切都很好 一个可能的问题是,您没有在ImageView内看到完整尺寸的图像,因为它会缩放它,因此您会看到比您想要的字体小的字体。
您可以在绘制文本之前调整图像大小以适合将显示的容器。 或者,您可以计算fontSize乘以1/scale,并scale = the scale at will the image will be shown
例如,如果图像高于较大且容器(imageView)小于图像比例,则为image.size.height/imageView.frame.size.height
我认为这可以解决您的问题。

答案 1 :(得分:0)

正如 LorenzOliveto 所建议的,这可能是由于缩放问题。一种简单的解决方法是将文本添加为​​ imageView 的子视图,然后使用此扩展程序将 imageView 转换为图像。

extension UIView {
    /**
     Convert UIView to UIImage
     */
    func toImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
        let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImageFromMyView!
    }
}