如何根据图像的大小动态设置imageView的大小

时间:2012-05-17 10:13:06

标签: iphone ipad uiimageview

我使用Interface Builder来布局我的视图和图像视图。我在视图上放了一个imageView并将其设置为插座。问题是无论我在我的程序中设置了什么尺寸的图像(768 * 1024,1024 * 700):

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

屏幕上的大小始终是我在Interface Builder中设置的imageView的大小。如何根据图像的大小动态设置imageView的大小?谢谢!

5 个答案:

答案 0 :(得分:4)

类似的东西:

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

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以对图像进行子类化,并为设置新图像的每个时间执行以下覆盖:

@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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

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

[ yourimageview setframe:rect];