【问题标题】:Retrieving UIImage from UIImageView sized accordingly从相应大小的 UIImageView 中检索 UIImage
【发布时间】:2014-11-13 23:22:11
【问题描述】:

如何从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; 

【问题讨论】:

  • 你想要获取图像还是想要图像边界(CGrect)?

标签: ios objective-c uiimageview uiimage


【解决方案1】:

你必须重新绘制图像然后保存它。

// 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

【讨论】:

  • 图像的大小调整为正确的宽高比,但大小比imageView 中的大小要小得多。这可能是什么原因造成的?
  • 你说的小得多是指长度和高度的一半吗?
  • 我明白了 :) 现在可以完美运行。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2011-09-16
  • 2013-01-16
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
相关资源
最近更新 更多