iphone - 如何从 UILabel 创建图像?

标签 iphone objective-c uiimage uilabel flatten

我目前正在 iPhone 上开发一个类似 photoshop 的简单应用程序。当我想展平我的图层时,标签位于正确的位置但字体大小不佳。 这是我要展平的代码:

UIGraphicsBeginImageContext(CGSizeMake(widthDocument,widthDocument));

for (UILabel *label in arrayLabel) {
    [label drawTextInRect:label.frame];
}

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

谁能帮帮我?

最佳答案

发件人:pulling an UIImage from a UITextView or UILabel gives white image .

//iOS

- (UIImage *)grabImage {
    // Create a "canvas" (image context) to draw in.
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);  // high res
    // Make the CALayer to draw in our "canvas".
    [[self layer] renderInContext: UIGraphicsGetCurrentContext()];

    // Fetch an UIImage of our "canvas".
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // Stop the "canvas" from accepting any input.
    UIGraphicsEndImageContext();

    // Return the image.
    return image;
}

//带用法的 Swift 扩展。在下面的评论中感谢@Heberti Almeida

extension UIImage {
    class func imageWithLabel(label: UILabel) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0)
        label.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

用法:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 22))
label.text = bulletString
let image = UIImage.imageWithLabel(label)

关于iphone - 如何从 UILabel 创建图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38382736/

相关文章:

iphone - 选择器值在部分中所有行的文本字段中重复?

objective-c - 如何创建 NSIndexPath :indexPathWithIndexes:length: 所需的 "indexes"

ios - 来自 NSFetchedResultsController 的 A-Z 索引,每个字母中都有单独的节标题?

ios - 将 UIImage 转换为 CIImage 时图像大小加倍

ios - 二元运算符 '!=' 不能应用于类型 "UIImage"的操作数

iphone - 关闭当前模态视图 Controller 的最优雅方式?

iphone - 在 iPhone 上以编程方式从 HTML 生成 PDF

iphone - 如何为大型数据集创建 UITableView 索引

objective-c - 无法使用 NSUserDefaults 保存 bool 变量

iphone - 返回时可能导致 [UIImage imageWithData] 崩溃的原因