Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

ios - How to get the size of a scaled UIImage in UIImageView?

The image.size attribute of UIImageView gives the size of the original UIImage. I would like to find out the size of the autoscaled image when it is put in the UIImageView (typically smaller than the original).

For example, I have the image set to Aspect Fit. Now I want to know its new height and width on the screen so I can draw accurately on the new scaled image.

Is there any way to do this without figuring it out myself based on the UIImageView size & UIImage original size (basically reverse engineering its scaling)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Objective-C:

-(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);
    }
}

Swift 4:

func frame(for image: UIImage, inImageViewAspectFit imageView: UIImageView) -> CGRect {
  let imageRatio = (image.size.width / image.size.height)
  let viewRatio = imageView.frame.size.width / imageView.frame.size.height
  if imageRatio < viewRatio {
    let scale = imageView.frame.size.height / image.size.height
    let width = scale * image.size.width
    let topLeftX = (imageView.frame.size.width - width) * 0.5
    return CGRect(x: topLeftX, y: 0, width: width, height: imageView.frame.size.height)
  } else {
    let scale = imageView.frame.size.width / image.size.width
    let height = scale * image.size.height
    let topLeftY = (imageView.frame.size.height - height) * 0.5
    return CGRect(x: 0.0, y: topLeftY, width: imageView.frame.size.width, height: height)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...