如何选择UIView的一部分来转换为UIImage



将UIView转换为UIImage

+(UIImage*) createUIImageFromView:(UIView *)view frame:(CGRect)frame;
{
    if (UIGraphicsBeginImageContextWithOptions != NULL)
    {
        UIGraphicsBeginImageContextWithOptions(frame.size, NO, 2.0f);
    }
    else
    {
        UIGraphicsBeginImageContext(view.frame.size);
    }
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

然而,我只能选择图像的大小,但不能选择UIView中应该转换为图像的位置。例如,如果我想转换矩形CGRect(10,10,20,20)而不是整个UIView,我该怎么做?

您可以在您的上下文中设置坐标转换矩阵。这允许你改变坐标系统,所以当图层在(0,0)处绘制时,它实际上会在上下文的其他地方渲染。您想要用来实际修改CTM的函数在CGContext文档的转换用户空间部分中有文档记录。

最新更新