Reputation: 5157
I have a UIButton that needs to change its image once the user has selected a photo from the photo album to show its selection, I have this setup up and running but once the user has selected a photo I need to resize it to the button dimensions and that is where I need help, here is my code:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *giftImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[giftImage resizableImageWithCapInsets:UIEdgeInsetsMake( 0, 10, 0, 10 )];
[giftButton setBackgroundImage:giftImage forState:UIControlStateNormal];
giftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
giftButton.imageView.contentMode = UIViewContentModeScaleToFill;
giftButton.imageView.bounds = CGRectMake( 0, 0, 62, 62 );
}
UPDATE: Found a solution, so far all that happen was that the button got resized to the image dimensions, but using the following code, I manage to insert the image inside at the size I need, it is a work in progress but is working ;)
CGSize targetSize = CGSizeMake( 62, 62 );
UIGraphicsBeginImageContext( targetSize );
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = CGPointMake( 0, 0 );
thumbnailRect.size.width = 62;
thumbnailRect.size.height = 62;
[giftImage drawInRect:thumbnailRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
[giftButton setBackgroundImage:newImage forState:UIControlStateNormal];
UIGraphicsEndImageContext();
The code is from this post Resize and crop images before displaying in UITableViewCells
Upvotes: 0
Views: 4562
Reputation: 209
You can try:
[giftButton setContentMode:UIViewContentModeScaleAspectFit];
and this should scale the image to fit nicely in your button
Upvotes: 2