如何按照aspectfit uiimageview尺寸制作边框图像?

时间:2012-08-25 13:05:55

标签: iphone uiimageview uiimage contentmode aspect-fit

在我的应用程序中我有2个uiimageview.one imageview包含用户从照片库中选择的图像或从相机拍摄照片。此imageview的内容模式是aspectfit,因此如果图像尺寸较小则不会拉伸图像。有其他图像视图包含与第一个图像视图边界的图像。当用户选择具有相似尺寸的图像视图的图像时,边框是合适的位置。但是当图像尺寸较小时,边框不正确。边框图像之间存在间隙和所选的照片image.i不要那个差距。我怎么能解决这个问题?See the attached image.Here i dont want black gap that is between image and frame

1 个答案:

答案 0 :(得分:3)

使用以下代码解决了这个问题:

-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
    float imageRatio = image.size.width / image.size.height;

    float viewRatio = imageView.frame.size.width / imageView.frame.size.height;

    if(imageRatio < viewRatio)
    {
        float scale = imageView.frame.size.height / image.size.height;

        float width = scale * image.size.width;

        float topLeftX = (imageView.frame.size.width - width) * 0.5;

        return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
    }
    else
    {
        float scale = imageView.frame.size.width / image.size.width;

        float height = scale * image.size.height;

        float topLeftY = (imageView.frame.size.height - height) * 0.5;

        return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
    }
}