我怎么能动态地根据图像的大小设置ImageView的大小(How can I dynamically

2019-10-28 11:45发布

我的用户界面生成器来布置我的观点和图像视图。 我把ImageView的视图上,并设置为一个出口。 问题是,不管是什么尺寸图像(768 * 1024,1024 * 700)我在程序中设置:

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

要在屏幕上的大小始终是我在Interface Builder中的ImageView的大小。 我怎么能动态地根据图像的大小设置ImageView的大小? 谢谢!

Answer 1:

就像是:

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

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

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


Answer 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);


Answer 3:

你可以继承你的形象和做eachTime新的图像设置以下重写:

@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


Answer 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)];


Answer 5:

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

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

[ yourimageview setframe:rect];


文章来源: How can I dynamically set the size of the imageView according to the size of the image