首页 文章

从相应大小的UIImageView中检索UIImage

提问于
浏览
0

如何从显示的大小(给定内容模式)中检索 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

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

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

相关问题