从相应大小的UIImageView中检索UIImage

时间:2014-11-13 23:22:12

标签: ios objective-c uiimageview uiimage

我如何从显示的imageView图像中检索图像(给定内容模式),而不是根据原生属性检索图像?

代码:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WID, WID)];
imageView.center = CGPointMake(point.x, point.y + Y_OFFSET);
imageView.image = [UIImage imageNamed:@"img"];
imageView.contentMode = UIViewContentModeScaleAspectFit; 

1 个答案:

答案 0 :(得分:0)

您必须再次绘制图像然后保存。

// Image frame size
CGSize size = imageView.bounds.size;
// Grab a new CGContext
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
// Draw the image
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
// Grab the new image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

上面的代码在框架中绘制图像,拉伸到边界。如果你想要任何其他的绘制方式,你必须自己计算它们并将所需的东西放在"绘制图像"代码行。

例如,对于纵横拟合,请​​查看此算法:

- (CGRect) aspectFittedRect:(CGSize)inSize max:(CGRect)maxRect {
    float originalAspectRatio = inSize.width / inSize.height;
    float maxAspectRatio = maxRect.size.width / maxRect.size.height;

    CGRect newRect = maxRect;
    if (originalAspectRatio > maxAspectRatio) { // scale by width
        newRect.size.height = maxRect.size.height * inSize.height / inSize.width;
        newRect.origin.y += (maxRect.size.height - newRect.size.height)/2.0;
    } else {
        newRect.size.width = maxRect.size.height  * inSize.width / inSize.height;
        newRect.origin.x += (maxRect.size.width - newRect.size.width)/2.0;
    }

    return CGRectIntegral(newRect);
}

只需将imageView.image.size作为inSizeimageView.bounds作为maxRect传递。

来源: http://iphonedevsdk.com/forum/iphone-sdk-development-advanced-discussion/15001-aspect-fit-algorithm.html