0

我有一个 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 displayed in UITableViewCells

4

1 回答 1

2

你可以试试:

[giftButton setContentMode:UIViewContentModeScaleAspectFit];

这应该缩放图像以很好地适合您的按钮

于 2012-11-18T19:52:22.347 回答