2011-06-17 101 views
7

我想创建一个UIPickerView,其中包含一些图像,但我似乎无法弄清楚如何让图像适合视图(现在它们太大了,相互重叠)。我试图使用函数来调整每个图像时,它的绘制,但我收到错误时,函数被调用,虽然程序编译和运行良好(图像不调整大小除外)。调整大小功能和初始化功能是:在UIImageView中调整UIImage的大小

-(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:invalid context

TabTempla te [29322]:CGBitmapContextCreateImage:无效的上下文

我找不出什么问题。任何帮助是极大的赞赏。

+0

情况下,你是否通过CGImageGetColorSpace(imageRef)返回的值是CGBitmapContextCreate接受的价值观吗? – Bemmu 2011-06-17 05:20:05

回答

15

使用以下比例使用纵横比的图像,然后裁剪图像到的ImageView的边界。

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

谢谢你的回答。 'clipsToBounds'是我错过的 - 巨大的帮助! – Sam 2013-03-23 20:54:49

+0

@Sam - 欢迎您:) – trillions 2013-03-24 05:42:35

+0

这将正确填充图像的视图,同时保持其纵横比,但隐藏不适合该区域的东西。 – 2017-05-09 06:26:26

0

在迅速

imageView.contentMode = .ScaleAspectFill 
imageView.clipsToBounds = true 
-1
UIImage *image = [UIImage imageNamed:@"myImage"]; 
    [image drawInRect: destinationRect]; 
    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext(); 
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);