OGeek|极客世界-中国程序员成长平台

标题: ios - view.layer drawInContext :UIGraphicsGetCurrentContext() not drawing [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 06:51
标题: ios - view.layer drawInContext :UIGraphicsGetCurrentContext() not drawing

我正在尝试将 UIView 绘制到 UIImage 中。这是我正在使用的代码:

UIGraphicsBeginImageContextWithOptions(myView.bounds.size, YES, 0.f);
[myView.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我已验证 myView.bounds.size 有效。 myView 在屏幕上正确显示。但是,img 完全是黑色的(我尝试在 UIImageView 中同时显示并尝试将 JPEG 表示写入文件。)图像尺寸正确,色彩空间(在 JPEG 文件输出中)是 RGB,颜色配置文件是 sRGB 等,这意味着我们不是在处理损坏的图像(在图像/位图数据本身有效的意义上)。我已经在 6.0 模拟器、7.0 模拟器和 7.0.6 设备上测试过这个案例,都一样。该图层没有任何子图层,我尝试将 masksToBounds 设置为 NO ,但没有任何改变。

什么可能导致 View 层不绘制?



Best Answer-推荐答案


你需要改变:

[myView.layer drawInContext:UIGraphicsGetCurrentContext()];

到:

[myView.layer renderInContext:UIGraphicsGetCurrentContext()];

请注意,drawInContext: 默认情况下实际上并没有做任何事情:

The default implementation of this method does not doing any drawing itself. If the layer’s delegate implements the drawLayer:inContext: method, that method is called to do the actual drawing.

Subclasses can override this method and use it to draw the layer’s content. When drawing, all coordinates should be specified in points in the logical coordinate space.

UIView 的层委托(delegate)被设置为 UIView,但它看起来并不像 UIView 必须绘制到提供的上下文。需要对此进行更多调查。

关于ios - view.layer drawInContext :UIGraphicsGetCurrentContext() not drawing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22286863/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4