渲染UIView内容以匹配另一个图像的分辨率

时间:2013-12-01 02:02:04

标签: ios uiview uiimageview

好的,这个设置有点复杂,让我看看能不能正确解释。

我有一个UIView - > BackgroundImageView - > ContainerView - > SmallerImageView

我有一个完整的分辨率(更高分辨率,然后原生屏幕)图像加载到UIimageView。我在SmallerImageview中有一个“叠加”图像。允许用户通过在屏幕上拖动来调整较小图像的位置。

我想创建一个与背景图像分辨率相同的图像,它只包含SmallerImageView中的对象。就像扩展图像的“画布大小”一样,但是将内容保留在相同的相对位置。我这样做是通过“渲染”包含子视图的容器视图。

我目前使用以下内容从ContainerView

创建图像
- (UIImage *) imageWithView:(UIView *)view {
     UIGraphicsBeginImageContextWithOptions(view.bounds.size,view.opaque,2);
     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();

     return img;
}

问题是容器视图为320x568(屏幕大小),背景图像为960x1280(像素分辨率)。它们是不同的方面比例,并且在UIGraphicsBeginImageContextWithOptions的调用中没有一个缩放因子可用于使两个大小匹配。

_mike

1 个答案:

答案 0 :(得分:0)

如果我理解你的要求是正确的(这是一个很大的问题),这应该做你想要的:

- (UIImage *)imageWithView:(UIView *)smallerView container:(UIView *)biggerView {
    // Create the image context the size you want it. The scale determines if
    // it's a "retina" image or not. Use 0 so it does the right thing on the
    // right devices.
    UIGraphicsBeginImageContextWithOptions(biggerView.bounds.size, NO, 0);
    CGContextRef c = UIGraphicsGetCurrentContext();

    // When you call [view renderInContext:], it renders it as if the top left
    // of the context you're rendering is the view's bounds.origin (usually
    // CGPointZero, but it can be different for views like UIScrollView. To
    // get around that, we have to figure out what the "top left" we want is.

    // First we find out how far our view's top left corner is offset from
    // the "big" view's top left corner. If we just used smallerView.frame.origin
    // without transforming it, it would be relative to the container view, which
    // isn't what we want.
    CGPoint topLeft = [biggerView convertPoint:smallerView.frame.origin fromView:smallerView.superview];

    // This offsets all subsequent drawing operations by the amount we
    // calculated.
    CGContextTranslateCTM(c, topLeft.x, topLeft.y);

    // Now we render the view at the right location.
    [smallerView.layer renderInContext:c];

    // Normal stuff
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

使用imageWithView:(UIView *)smallerImageView container:backgroundImageView调用它,它应该做你想要的。