根据宽度调整UIImage的大小

时间:2014-08-12 14:42:36

标签: ios objective-c uiimage uicollectionview

我有一个包含多个UIImage对象的NSMutableArray,这些对象包含不同的维度,它们都需要宽度为140,但这会使我的UICollectionView中的图像非常糟糕。

有没有一种方法可以放入UIImage,然后设置宽度140,然后获得新高度,这是我需要的单元格高度?

1 个答案:

答案 0 :(得分:1)

工作代码:

    //create image array
    UIImage *image = [UIImage imageNamed:@"yourimagename.png"];
    NSArray *imageArray = [NSArray arrayWithObjects:image, nil];


    //get image original height, original width...
    CGFloat originalHeight = image.size.height;
    CGFloat originalWidth = image.size.width;

    //set wanted width and calculate wanted height...
    CGFloat wantedWidth = 140;
    CGFloat wantedHeight = (originalHeight*wantedWidth)/originalWidth;

    //call resize image method... setting wanted height and width....
    UIImage *avatarImage = [self imageWithImage:[imageArray objectAtIndex:0] scaledToSize:CGSizeMake(wantedWidth, wantedHeight)];
    //create imageView.. ... .
    UIImageView *avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, wantedWidth, wantedHeight)];
    [avatarImageView setImage:avatarImage];
    [self.view addSubview:avatarImageView];

调整图像方法大小。

- (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}