2012-09-23 92 views
23

我对于目标c非常陌生,而且我只是接受了我的轴承。我想做一些非常简单的事情,但它证明是一个相当大的挑战:调整图像大小以适合UIImageView

我想显示图像到UIImageView。我展示的图片很大,我希望它缩小到适合UIImageView。我尝试设置AspectFit查看模式,但图像显示为原始尺寸,并由UIImageView剪辑。我的代码如下:

- (void)changeImages 
{ 
    UIImage* img11 = nil; 

    img11 = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"jpeg"]]; 

    u11.contentMode = UIViewContentModeScaleAspectFit; 
    u11.image = img11; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    [self changeImages]; 
} 

任何人都可以对此有所了解吗?

谢谢!

+1

你看过http://stackoverflow.com/questions/185652/how-to-scale-a -uiimageview-proportionally? 特别是第二个答案可能是有趣的。 –

+0

所有权利,这应该工作。需要检查的内容:您是否已经将图像设置在笔尖/故事板中?如果是这样,这可能掩盖代码不被调用。 changeImages被叫?你可以调用'NSLog(@“changeImages called”)'来查看它是否或者使用断点。如果不是,您可能忘记将nib/storyboard中ViewController的类更改为您上面编写的代码的类。是否将'u11'指定为IBOutlet并正确链接到笔尖/故事板? – Xono

+0

如果你对目标c很陌生,最好的办法就是使用第三个关于图像大小调整的函数库,比如https://github.com/mattgemmell/MGImageUtilities – martinezdelariva

回答

31

您好我想尝试这个...

- (void)changeImages 
{ 
    UIImage *img11 = [UIImage [email protected]"dog.jpeg"]; 

    u11.contentMode = UIViewContentModeScaleAspectFit; 
    u11.clipsToBounds = YES; 
    [u11 setImage:img11]; 
} 

- (void)viewWillAppear:animated 
{ 
    [super viewWillAppear:animated]; 

    [self changeImages]; 
} 

这会缩小图片(向上或向下),因此它适合ImageView的内部。拥有clipsToBounds并不是必须的,但会阻止图像在您的imageView框架外显示。

HTH。

4
CGSize size=CGSizeMake(79, 84);//set the width and height 
UIGraphicsBeginImageContext(size); 
[image drawInRect:CGRectMake(0,0,size.width,size.height)]; 
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext(); 
//here is the scaled image which has been changed to the size specified 
UIGraphicsEndImageContext(); 

这个工程肯定的,不要忘了导入QuartzCore框架..

有一个幸福的编码(^ _ ^)......

+0

用于Quartz方法。它比标准的'UIKit' contentMode属性更好地调整大小。 – danielbeard

+0

真的很好,谢谢:) –

16

添加到您的UIViewController.m:

-(UIImage *)resizeImage:(UIImage *)image imageSize:(CGSize)size 
{ 
    UIGraphicsBeginImageContext(size); 
    [image drawInRect:CGRectMake(0,0,size.width,size.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    // here is the scaled image which has been changed to the size specified 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 

使用:

UIImage *image = [UIImage imageNamed:@"image.png"]; 
CGSize size = CGSizeMake(50, 63); // set the width and height 
UIImage *resizedImage = [self resizeImage:image imageSize:size]; 

我希望它有帮助。

+0

所以,如果我有一个UITableView从网上获取我的数据填充UITableViewCells图片,我想调整我的图像这种方式来提高性能,我是否在cellForRowAtIndexPath中调用此方法? –

1

您还可以设置视图:模式看点飞度在属性检查器在Interface Builder

0

我做了以下内容和它帮助 变化的模式从默认值“方面填补”“规模,以填补”

,并添加一行代码如下(我做了它在细胞配置):

cell.photo.clipsToBounds = true