当视图在其边界之外绘制时,将UIView渲染为图像

时间:2014-03-11 00:59:03

标签: ios iphone

我想将UIView呈现给图像。我的首选UIView类别是

- (UIImage *)num_renderToImage
{
    UIGraphicsBeginImageContext(self.bounds.size);

    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

然而在这种情况下,UIView具有在其边界之外绘制的元素,并且上面的剪辑它们。改变传递给UIGraphicsBeginImageContext的大小没有帮助,因为大小向下和向右增长,但这些元素在上方和左侧。什么是正确的方法?

2 个答案:

答案 0 :(得分:4)

在上面的场景中,如果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写入文件中。您可以根据需要进行调整。)

答案 1 :(得分:0)

如果有人遇到问题,我会在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)
}