使用renderInContext时UILabel文本不是渲染器

使用renderInContext时UILabel文本不是渲染器

本文介绍了swift - 异步使用renderInContext时UILabel文本不是渲染器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从由 UIImageView UILabel 组成的自定义视图生成图像。

I need to generate an image from a custom view composed by an UIImageView and an UILabel.

我无法使用新的iOS 7 drawViewHierarchyInRect:afterScreenUpdates:因为我在iPhone 6/6 +上有一些难看的小故障()

I can't use the new iOS 7 drawViewHierarchyInRect:afterScreenUpdates: because I have some ugly glitch on iPhone 6/6+ (iOS8 scale glitch when calling drawViewHierarchyInRect afterScreenUpdates:YES)

所以我用旧时尚的方式使用 renderInContext:这样做效果很好,但速度很慢。我正在使用图像生成来显示 GMSMapView 中的标记(上帝我错过了 MapKit ...)但用户由于图像生成滞后,经验非常糟糕。

So I did it the old fashion way using renderInContext: which works well but it's quite slow. I'm using image generation to display markers in a GMSMapView (god I missed MapKit ...) but the user experience is quite bad because of lags due to those image generation.

所以我尝试在后台线程中执行图像创建操作,以便有一些平滑但是这里是问题:我的大多数标签都没有呈现。

So I try to perform the image creation operation in a background thread in order to have something smooth but here's the problem : the majority of my labels are not rendered.

任何人已经遇到过这个问题?

Anyone as already faced this issue ?

这是我使用的代码:

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 似乎存在问题。

您最好的选择是使用方法 NSString 绘制你的文字。

It seems there are issues to rendering UILabel in an other thread than the main one.
Your best option is to use the method drawInRect:withAttributes: of NSString to draw your text.

这篇关于swift - 异步使用renderInContext时UILabel文本不是渲染器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:38