文字大小与图像大小成正比

时间:2016-03-30 01:54:13

标签: ios xcode swift2

我希望我的文字大小与我的图片大小成正比

我想在这段代码中做到这一点......

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
    }
}

0 个答案:

没有答案