0

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!

itenyh
  • 1,921
  • 2
  • 23
  • 38

5 Answers5

4

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);
Son Nguyen
  • 3,481
  • 4
  • 33
  • 47
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);
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
waheeda
  • 1,097
  • 1
  • 9
  • 18
1

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
Vaseltior
  • 1,226
  • 15
  • 27
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)];
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
Saad
  • 8,857
  • 2
  • 41
  • 51
0
UIImage* sourceImage = [UIImage imageNamed:self.filename];;

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

[ yourimageview setframe:rect];
Surender Rathore
  • 845
  • 8
  • 18