问题
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