How can I dynamically set the size of the imageView according to the size of the image

巧了我就是萌 提交于 2019-12-11 19:19:32

问题


I user Interface Builder to layout my view and image view. I put a imageView on the view and set it as an outlet. The problem is that no matter what size of image (768*1024、1024*700) I set in my program:

 self.imageView.image = [UIImage imageNamed:self.filename];

The size to be on the screen is always the size of the imageView I set in the Interface Builder. How can I dynamically set the size of the imageView according to the size of the image? Thanks!


回答1:


Something like:

UIImageView *imageView = [[UIImageView alloc] init];

UIImage *image = [UIImage imageNamed:@"image.png"];
CGSize imageSize = [image size];

imageView.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);



回答2:


UIImage *image = [UIImage imageNamed:self.filename];
CGFloat width = image.size.width;
CGFloat height = image.size.height;
self.imageView.frame = CGRectMake(x, y , width, height);



回答3:


You could subclass your image and do the following override for eachTime a new image is set :

@interface MyImageSubClass : UIImageView;
@end

@implementation MyImageSubClass

- (void)setImage:(UIImage *)image {
    // Let the original UIImageView parent class do its job
    [super image];

    // Now set the frame according to the image size
    // and keeping the original position of your image frame
    if (image) {
        CGRect r = self.frame;
        CGSize imageSize = [image size];
        self.frame = (r.origin.x, r.origin.y, imageSize.width, imageSize.height);
    }
}

@end



回答4:


 UIImage *buttonImage2=[UIImage imageNamed:@"blank_button_blue.png"];
 oButton=[[UIButton alloc] init];
 //  [oButton setImage:buttonImage2 forState:UIControlStateNormal];
 [oButton setFrame:CGRectMake(0, 0, buttonImage2.size.width, buttonImage2.size.height)];



回答5:


UIImage* sourceImage = [UIImage imageNamed:self.filename];;

 CGRect rect;
rect.size.width = CGImageGetWidth(sourceImage.CGImage);
 rect.size.height = CGImageGetHeight(sourceImage.CGImage);

[ yourimageview setframe:rect];


来源:https://stackoverflow.com/questions/10633720/how-can-i-dynamically-set-the-size-of-the-imageview-according-to-the-size-of-the

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