在我的应用程序中,用户使用 UIImagePickerViewController 选择图像或拍照。选择图像后,我想在方形 UIImageView (90x90) 上显示其缩略图。
我正在使用Apple 的代码来创建缩略图。问题是缩略图不是平方的,该函数在将 kCGImageSourceThumbnailMaxPixelSize 键设置为 90 后,似乎只是调整图像的高度,据我所知 kCGImageSourceThumbnailMaxPixelSize 键应该负责设置缩略图的高度和宽度。
这是我的代码的一瞥:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
// My image view is 90x90
UIImage *thumbImage = MyCreateThumbnailImageFromData(imageData, 90);
[myImageView setImage:thumbImage];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
UIImage* MyCreateThumbnailImageFromData (NSData * data, int imageSize) {
CGImageRef myThumbnailImage = NULL;
CGImageSourceRef myImageSource;
CFDictionaryRef myOptions = NULL;
CFStringRef myKeys[3];
CFTypeRef myValues[3];
CFNumberRef thumbnailSize;
// Create an image source from NSData; no options.
myImageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data,
NULL);
// Make sure the image source exists before continuing.
if (myImageSource == NULL){
fprintf(stderr, "Image source is NULL.");
return NULL;
}
// Package the integer as a CFNumber object. Using CFTypes allows you
// to more easily create the options dictionary later.
thumbnailSize = CFNumberCreate(NULL, kCFNumberIntType, &imageSize);
// Set up the thumbnail options.
myKeys[0] = kCGImageSourceCreateThumbnailWithTransform;
myValues[0] = (CFTypeRef)kCFBooleanTrue;
myKeys[1] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
myValues[1] = (CFTypeRef)kCFBooleanTrue;
myKeys[2] = kCGImageSourceThumbnailMaxPixelSize;
myValues[2] = thumbnailSize;
myOptions = CFDictionaryCreate(NULL, (const void **) myKeys,
(const void **) myValues, 2,
&kCFTypeDictionaryKeyCallBacks,
& kCFTypeDictionaryValueCallBacks);
// Create the thumbnail image using the specified options.
myThumbnailImage = CGImageSourceCreateThumbnailAtIndex(myImageSource,
0,
myOptions);
UIImage* scaled = [UIImage imageWithCGImage:myThumbnailImage];
// Release the options dictionary and the image source
// when you no longer need them.
CFRelease(thumbnailSize);
CFRelease(myOptions);
CFRelease(myImageSource);
// Make sure the thumbnail image exists before continuing.
if (myThumbnailImage == NULL) {
fprintf(stderr, "Thumbnail image not created from image source.");
return NULL;
}
return scaled;
}
这就是我的图像视图的实例化方式:
myImageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeScaleAspectFit;
CGRect rect = imageView.frame;
rect.size.height = 90;
rect.size.width = 90;
imageView.frame = rect;
[imageView setUserInteractionEnabled:YES];
如果我不设置imageView.contentMode = UIViewContentModeScaleAspectFit;
缩略图会失真,因为它只是我原始图像的一个版本,高度为 90 像素。
那么,为什么我的缩略图不是方形的?