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

 

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

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

复制代码
-(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];
复制代码

原文地址:https://www.cnblogs.com/bugismyalllife/p/4826124.html