在UIImageView中调整UIImage的大小

8

我正在尝试创建一个带有图像的UIPickerView,但是我似乎无法弄清楚如何使图像适合视图(现在它们太大并且重叠在一起)。

我正在尝试使用一个函数来调整每个图像在绘制时的大小,但是当调用该函数时,我会遇到错误,尽管程序编译和运行正常(除了图像不会调整大小)。 调整大小函数和初始化函数如下:

-(UIImage *)resizeImage:(UIImage *)image width:(int)width height:(int)height {
    NSLog(@"resizing");
    CGImageRef imageRef = [image CGImage];
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
    
    //if (alphaInfo == kCGImageAlphaNone)
    alphaInfo = kCGImageAlphaNoneSkipLast;
    
    CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 
                                                4 * width, CGImageGetColorSpace(imageRef), alphaInfo);
    CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage *result = [UIImage imageWithCGImage:ref];
    
    CGContextRelease(bitmap);
    CGImageRelease(ref);
    
    return result;  
}

- (void)viewDidLoad {
    UIImage *h1 = [UIImage imageNamed:@"h1.png"];
    
    h1 = [self resizeImage:h1 width:50 height: 50];
    
    UIImageView *h1View = [[UIImageView alloc] initWithImage:h1];
        
    NSArray *imageViewArray = [[NSArray alloc] initWithObjects:
                                h1View, nil];
    
    NSString *fieldName = [[NSString alloc] initWithFormat:@"column1"];
    [self setValue:imageViewArray forKey:fieldName];
    [fieldName release];
    [imageViewArray release];
        
    [h1View release];
}

控制台输出:

TabTemplate[29322:207] 正在调整大小

TabTemplate[29322] : CGBitmapContextCreate:不支持的颜色空间

TabTemplate[29322] : CGContextDrawImage:无效上下文

TabTemplate[29322] : CGBitmapContextCreateImage:无效上下文

我无法弄清楚哪里出了问题。非常感谢您的帮助。


你有检查过CGImageGetColorSpace(imageRef)返回的值是否是CGBitmapContextCreate接受的值之一吗? - Bemmu
4个回答

17

14

使用以下代码按照宽高比缩放图像,然后将其裁剪为ImageView的边界。

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES; 

1
谢谢你的回答。clipsToBounds是我所缺少的 - 帮了大忙! - StoriKnow
1
这将正确地填充视图与图像,同时保持其纵横比,但隐藏不适合区域的部分。 - Ammar Mujeeb

0

如果是Swift语言

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true

-1
UIImage *image = [UIImage imageNamed:@"myImage"];
    [image drawInRect: destinationRect];
    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接