如何在Swift中的图像中放置文本?

时间:2016-03-27 00:50:36

标签: objective-c swift

我正在制作应用,所以我需要知道如何在图像中添加一些文字 我正在使用Xcode 7和Swift 2

我已经有了这个代码,但它在Objective-C中并且我不知道它是否有效...

- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img {
    UIGraphicsBeginImageContext(img.size);

    CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
    [img drawInRect:aRectangle];

    [[UIColor redColor] set];
    NSInteger fontSize = 14;
    if ( [text length] > 200 ) {
        fontSize = 10;
    }
    UIFont *font = [UIFont boldSystemFontOfSize: fontSize];

    [text drawInRect : aRectangle
            withFont : font
       lineBreakMode : UILineBreakModeTailTruncation
           alignment : UITextAlignmentCenter ];

    UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

1 个答案:

答案 0 :(得分:1)

我尝试将代码翻译成Swift 2.这和我一样接近:

extension UIImage {
    func withText(text: String) -> UIImage {
        UIGraphicsBeginImageContext(size)

        let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        drawInRect(rectangle)

        UIColor.redColor().set()
        let fontSize = text.characters.count > 200 ? 10 : 14
        let font = UIFont.boldSystemFontOfSize(CGFloat(fontSize))

        let attributes: [String: AnyObject] = [
            NSFontAttributeName: font
        ]
        (text as NSString).drawInRect(rectangle, withAttributes: attributes)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

正如您所看到的,NSString的{​​{1}}现在需要drawInRect来获取其属性。我无法找到[String: AnyObject]?lineBreakMode的相应密钥。

正如documentation所述:

  

这些属性可以应用于alignment对象...

更新

我添加了其他规格:

NSAttributedString

只是因为之前不清楚......这就是你如何使用这个方法:

extension UIImage {
    func withText(text: String) -> UIImage {
        UIGraphicsBeginImageContext(size)

        let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        drawInRect(rectangle)

        let fontSize = text.characters.count > 200 ? 10 : 14
        let font = UIFont.boldSystemFontOfSize(CGFloat(fontSize))

        let paragraphAttributes = NSMutableParagraphStyle()
        paragraphAttributes.lineBreakMode = NSLineBreakMode.ByTruncatingTail
        paragraphAttributes.alignment = NSTextAlignment.Center

        let attributes: [String: AnyObject] = [
            NSFontAttributeName: font,
            NSForegroundColorAttributeName: UIColor.redColor(),
            NSParagraphStyleAttributeName: paragraphAttributes
        ]
        (text as NSString).drawInRect(rectangle, withAttributes: attributes)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}