我想将 UIView 渲染为图像。我的首选 UIView 类别是
- (UIImage *)num_renderToImage
{
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
但是,在这种情况下, UIView 具有在其边界之外绘制的元素,并且上面的内容会对其进行剪辑。更改传递给
UIGraphicsBeginImageContext
的大小无济于事,因为大小会向下和向右增长,但这些元素位于上方和左侧。这样做的正确方法是什么? 最佳答案
在上面的场景中,使用 UIView
剪辑超出其边界的 UIButton
,您可以尝试:
- (IBAction)snapshot:(id)sender {
UIButton *button = sender;
UIView *v = button.superview;
// Prepare the rectangle to be drawn
CGRect allTheViews = CGRectUnion(v.bounds, button.frame);
UIGraphicsBeginImageContext(allTheViews.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// This is what you differently
CGContextTranslateCTM(context, -allTheViews.origin.x, -allTheViews.origin.y);
// This part is the same as before
[v.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[UIImagePNGRepresentation(img) writeToFile:@"/tmp/foo.png" atomically:NO];
}
在这里,我们将要绘制的内容结合起来,然后翻译 CTM,使其在我们绘制的图形上下文中可见。
(特别是这个例子,与按钮的 Action Hook ,并将按钮的
UIImage
和包含 View 的内容写入文件。您可以根据需要进行调整。)关于ios - 当 View 超出其边界时将 UIView 渲染为图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22314424/