How to make UIImageView automatically resize to the size of the image loaded

瘦欲@ 提交于 2019-11-28 05:56:14
Hampus Nilsson

The size of an image has no bearing on how large the UIImageView actually is, rather the size of the UIImageView solely depends on the size given to it in Interface Builder (or that you assigned to it). Else the images would be all whacky when you use the @2x images for Retina displays for example.

If you want to fix this, you must change the frame when setting the image as well. If you're doing this now:

[imageView setImage:[UIImage imageNamed:@"myImage.jpg"]];

change it to:

UIImage img = [UIImage imageNamed:@"myImage.jpg"];
[imageView setImage:img];
imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y,
                             img.size.width, img.size.height);

This will however not change the layout of view it is contained within, you can make it change the sizes of the other views automatically under iOS 6 using Layout Constraints. If you are an Apple Developer you can watch the WWDC instruction videos, they explain how that system works quite well.

If you're fine with the view not growing, and the problem is just how the image overflows it's bounds when you change it to one that does not match the dimension of the containing view, you can set the "Clip Subviews" checkbox in Interface Builder for the image view. This will make it so that the view will not draw anything outside it's own bounding box, if you also set the scaling mode to "Aspect Fill" or "Scale To Fill", the image will always fill up the entire bounds of the containing view.

Here is the code snippet I cut and paste often, using the same method as Hampus Nilsson above -

Example

func demo(x0:CGFloat, y0:CGFloat) {
    let imgView = UIImageView(image: UIImage(named: "someImg.png"));
    imgView.sizeToImage();
    imgView.center = CGPoint(x:x0, y:y0);
}

UIImageView Extension

extension UIImageView {

/******************************************************************************/
/** @fcn        sizeToImage()
 *  @brief      size view to image
 *  @@assum     (image!=nil)
 */
/******************************************************************************/
func sizeToImage() {

    //Grab loc
    let xC = self.center.x;
    let yC = self.center.y;

    //Size to fit
    self.frame  = CGRect (x: 0, y: 0, width: (self.image?.size.width)!/2, height: (self.image?.size.height)!/2);

    //Move to loc
    self.center = CGPoint(x:xC, y:yC);

    return;
}

A wonderful cut & paste, use if needed!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!