我正在尝试解决无法在 Watchkit 中使用自定义 UI 元素的问题。我的应用程序使用自定义 UIButtons (MRoundedbutton),我想做的是通过创建它们的图像并将其用作 WKInterfaceButton 的背景,在 Watchkit 界面上复制它们。问题是当 View 不可见时,我无法将 UIView 转换为 UIImage。这是我正在使用的代码,它在 drawViewHierarchyInRect
上给我一个索引越界错误。
- (UIImage *)convertButtontoImage:(MRoundedButton *)button
{
UIGraphicsBeginImageContextWithOptions(button.bounds.size, YES, 0);
[button drawViewHierarchyInRect:button.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
由于 Watchkit 扩展中确实没有屏幕/窗口,我们将如何从可能的 View 创建图像?
最佳答案
尝试在图层上使用 renderInContext 而不是 drawViewHierarchyInRect。
我刚刚遇到了您描述的相同问题。使用 drawViewHierarchInRect 不起作用 - 只是黑屏。但是在切换到 renderInContext 之后,看起来我能够在我的应用程序处于后台时将 UIView 转换为 UIImage(因此 View 在屏幕上不可见),然后我可以将它发送到 watch 并且它是显示。
这是我用过的:
+ (UIImage *)imageFromView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return capturedImage;
}
然后我使用 WatchKit Extension 中的 openParentApplication 来 ping 电话,然后将 UIImage 转换为 NSData,以便将其传回 handleWatchKitExtensionRequest。到目前为止,它似乎对我有用,所以希望它也对你有用。顺便说一句,这都是在模拟器上完成的。
关于ios - UIView --> 不可见 View 的 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29085957/