繁体   English   中英

当视图超出其边界时将 UIView 渲染为图像

[英]Rendering UIView to image when view draws outside its bounds

我想将 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,使其在我们绘制的图形上下文中可见。

(特别是这个例子,与按钮的动作相关联,并将按钮的UIImage和包含视图的内容写入文件。您可以根据需要进行调整。)

如果有人遇到问题,我在 Swift 5.0 中制作了这个更通用的版本。 只需将偏移量设置为您想要的值:

private func snapshotView(cell:UIView) -> UIImageView
{
        // by how much extra point out of the view bounds you want to draw your snapshot 
        let offset:CGFloat = 10
        

        let frame = cell.bounds.union(CGRect(x:-offset * 2.0,y:-offset * 2.0,
                          width:cell.bounds.width,
                          height: cell.bounds.height)).size 
        UIGraphicsBeginImageContextWithOptions(frame, false ,0)
        let context = UIGraphicsGetCurrentContext()
        context!.translateBy(x: offset, y: offset);
        cell.layer.render(in: context!)
        let snapshotImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
       
        return UIImageView(image: snapshotImage)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM