调整UIImageView的大小

时间:2013-04-24 21:35:59

标签: ios objective-c uiimageview cgrect

我有一个UIImageView的视图。我正从服务器检索宽300像素,高100像素的图像。但是,当我将图像插入UIImageView时,图像会被拉伸到图像视图的大小。

代码viewDidLoad:

id path = @"URL TO IMAGE";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];

CGRect frame = [imageView frame];
frame.size.width = 300;
frame.size.height = 100;
[imageView setFrame:frame];

self.imageView.image = img;

但是,UIImageView尺寸未更改为上述代码第6行和第7行中的值。

我感谢任何建议,我对Objective-C很新。

·H:

#import <UIKit/UIKit.h>

@interface detailViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *imageView;

1 个答案:

答案 0 :(得分:3)

您需要设置UIImageView的contentMode。查看contentMode的UIView文档,查看可以使用的不同值。例如,UIViewContentModeScaleToFill拉伸图像以完全匹配UIImageView的大小; UIViewContentModeCenter根本不会改变图像的大小;等等。

编辑:对于UIImageView本身,你需要确保你的引用都正确指向相同的UIImageView,并且这是来自nib的相同的UIImageView。此外,如果启用了Autolayout nib,则setFrame:将无效,因为该帧由约束决定。