您的位置:首页 > 移动开发 > IOS开发

iOS学习-压缩图片(改变图片的宽高)

2015-09-21 14:38 495 查看

压缩图片,图片的大小与我们期望的宽高不一致时,我们可以将其处理为我们想要的宽高。

传入想要修改的图片,以及新的尺寸

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);

// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

// End the context
UIGraphicsEndImageContext();

// Return the new image.
return newImage;
}


像button自带的imageView属赋图片时,若图片过大会自动压缩,导致失真(有时不能小到我们期望的)。如我在iOS学习-UIButton的imageView和titleLabel


宽高够大时是没有问题的,但我把button的titleLabel.font设小(12),宽高设小(高度设为30或更小)时就有问题了

,是不是觉得后面的图片太大了,

而图片的宽高又不好直接改,这时我们就可以先把图片给做小点,在加上就OK了。

  UIImage *buttonImage = [UIImage imageNamed:image];
//压缩图片大小
buttonImage = [self imageWithImage:buttonImage scaledToSize:CGSizeMake(20, 20)];

CGFloat buttonImageViewWidth = CGImageGetWidth(buttonImage.CGImage)
;
CGFloat buttonImageViewHeight = CGImageGetHeight(buttonImage.CGImage);

NSString *buttonTitle = title;

UIFont *buttonTitleFont = [UIFont boldSystemFontOfSize:12.0f];


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: