ios - swift - 异步使用 renderInContext 时 UILabel 文本不是渲染器

标签 ios image swift uiview rendering

我需要从由 UIImageViewUILabel 组成的自定义 View 生成图像。

我不能使用新的 iOS 7 drawViewHierarchyInRect:afterScreenUpdates: 因为我在 iPhone 6/6+ ( iOS8 scale glitch when calling drawViewHierarchyInRect afterScreenUpdates:YES ) 上有一些丑陋的故障

所以我使用 renderInContext: 以老式的方式完成了它,效果很好,但速度很慢。我正在使用图像生成在 GMSMapView 中显示标记(天哪,我错过了 MapKit ...)但是由于这些图像生成导致的延迟,用户体验非常糟糕.

所以我尝试在后台线程中执行图像创建操作,以便顺利进行,但问题是:我的大部分标签都没有呈现。

有人遇到过这个问题吗?

这是我使用的代码:

func CGContextCreate(size: CGSize) -> CGContext {
    let scale = UIScreen.mainScreen().scale
    let space: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()

    let bitmapInfo: CGBitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let context: CGContext = CGBitmapContextCreate(nil, Int(size.width * scale), Int(size.height * scale), 8, Int(size.width * scale * 4), space, bitmapInfo)
    CGContextScaleCTM(context, scale, scale)
    CGContextTranslateCTM(context, 0, size.height)
    CGContextScaleCTM(context, 1, -1)

    return context
}

func UIGraphicsGetImageFromContext(context: CGContext) -> UIImage? {
    let cgImage: CGImage = CGBitmapContextCreateImage(context)
    let image = UIImage(CGImage: cgImage, scale: UIScreen.mainScreen().scale, orientation: UIImageOrientation.Up)

    return image
}

extension UIView {
    func snapshot() -> UIImage {
        let context = CGContextCreate(self.frame.size)
        self.layer.renderInContext(context)
        let image = UIGraphicsGetImageFromContext(context)
        return image!
    }

    func snapshot(#completion: UIImage? -> Void) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let image = self.snapshot()
            completion(image)
        }
    }
}

最佳答案

在主线程之外的其他线程中渲染 UILabel 似乎存在问题。
您最好的选择是使用方法 drawInRect:withAttributes: NSString 来绘制你的文本。

关于ios - swift - 异步使用 renderInContext 时 UILabel 文本不是渲染器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512053/

相关文章:

ios - 在非父 View 的 UIView 中获取 View 的框架

ios - AWS AppSync 订阅 iOS 的特定设备/用户?

HTML:嵌入没有 base64 压缩的二进制图像

php - 如何将图像移动到新文件夹?

ios - 具有相同 XIB 单元格和按钮的多个 Collection View

ios - 如何在协议(protocol)中设置读写内部、只读外部属性

ios - 在同一个 View Controller 上按下 AlertViewController 上的确定按钮后重新加载 Collection View ?

php - 旋转并将图像的旋转存储在 php/mysql 网站中?

数组作为 Swift 字典中的值 : Cannot append values

iphone - 如何为 View 设置背景图像?