如何调整自定义UIButton的图像大小?

时间:2012-11-18 19:33:56

标签: objective-c ios uibutton uiimage

我有一个UIButton需要更改其图像,一旦用户从相册中选择了一张照片以显示其选择,我已经设置并运行但是一旦用户选择了照片,我需要将其调整为按钮尺寸,这是我需要帮助的地方,这是我的代码:

-(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 );
}

更新: 找到了一个解决方案,到目前为止所发生的一切都是按钮被调整大小到图像尺寸,但是使用下面的代码,我设法以我需要的尺寸插入图像,这是一个正在进行的工作但是正在工作;)

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();

代码来自此帖子Resize and crop images before displaying in UITableViewCells

1 个答案:

答案 0 :(得分:2)

您可以尝试:

[giftButton setContentMode:UIViewContentModeScaleAspectFit];

这应该缩放图像以适应你的按钮