Resizing UIImage in UIImageView
I'm trying to create a UIPickerView with some images in it, but I can't seem to figure out how to get the images to fit in the view (right now they're too large and are overlapping each other).
I'm trying to use a function to resize each image when it's drawn, but I'm getting errors when the function is called, although the program compiles and runs fine (with the exception of the image not resizing). The resizing function and initialization functions are:
-(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];
}
Console Output:
TabTemplate[29322:207] resizing
TabTemplate[29322] : CGBitmapContextCreate: unsupported colorspace
TabTemplate[29322] : CGContextDrawImage: invalid context
TabTemplate[29322] : CGBitmapContextCreateImage: invalid context
I can't figure out what's going wrong. Any help is greatly appreciated.
You don't require to resize your UIImage
if you use the contentMode
property of UIImageView
.
myImageView.contentMode = UIViewContentModeScaleAspectFit;
Or if you still want to resize your UIImage, Have look at below SO post.
resizing a UIImage without loading it entirely into memory?
UIImage: Resize, then Crop
Use below to scale the image using aspect ratio, then clip the image to imageview's bounds.
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
In case of swift
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
UIImage *image = [UIImage imageNamed:@"myImage"];
[image drawInRect: destinationRect];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);
精彩评论