以编程方式从 UILabel 创建图像 [英] Programmatically create image from UILabel

查看:21
本文介绍了以编程方式从 UILabel 创建图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 UILabel 以编程方式(在运行时)创建字节图像表示的 RGBA 流.

I want to use a UILabel to create an RGBA stream of bytes image representation programmatically (at runtime).

例如,我想创建一个特定字体和特定文本的 UILabel,将其转换为 RGBA 无符号字节的 NSData,然后我可以轻松地将其转换为 OpenGL 纹理并显示它但是我想要.

For example, I want to create a UILabel in a specific font and with specific text, turn this in to an NSData of RGBA unsigned bytes, and then from that point I can easily turn it in to an OpenGL texture and display it however I want.

知道生成图像的尺寸很重要,但如果绝对必要,我可以创建一个非常宽的空白"画布来渲染它,然后在运行时通过检查字节自己检测宽度和高度.

It's important that I can know the dimensions of the resulting image, although if absolutely necessary I can create a very wide "blank" canvas to render this in to, and then at runtime detect the width and height myself by checking the bytes.

如果我可以通过 UIImage/CG 实现这一点,那绝对是一个优势 - 具有多个渲染目标的解决方案是不合理/不理想的.

If I can achieve this through UIImage/CG it's a definite plus - and a solution with multiple render targets isn't reasonable/desired.

悬赏;我最初是从 meronix 那里得到这个好看的答案,但现在我有时间尝试一下,但它不能正常工作.我在昨天"需要这个工作并且非常沮丧.这里有一些细微差别,比我更了解 Cocoa 绘图状态的人肯定能捕捉到.

Placed a bounty; I had originally gotten this good-looking answer below from meronix, but now I got time to try it out and it does not work properly. I need this working "yesterday" and am quite frustrated. There's some nuance here, that someone who knows Cocoa drawing state better than me can surely catch.

推荐答案


CGFloat scale  = [[[view window] screen] scale];
CGRect  bounds = [view bounds];

CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL, CGRectGetWidth(bounds) * scale, CGRectGetHeight(bounds) * scale, 8, CGRectGetWidth(bounds) *
scale * 4, space, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(ctx, 0.0, CGRectGetHeight(bounds) * scale);
CGContextScaleCTM(ctx, scale, -scale);
[[view layer] renderInContext:ctx];

然后,通过 CGBitmapContextGetData(myContext) 使用字节.没有理由为 UIImage 烦恼

Then, use the bytes via CGBitmapContextGetData(myContext). No reason to bother with a UIImage

这篇关于以编程方式从 UILabel 创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆