iOS學習-壓縮圖片(改變圖片的寬高)

壓縮圖片,圖片的大小與咱們指望的寬高不一致時,咱們能夠將其處理爲咱們想要的寬高。html

傳入想要修改的圖片,以及新的尺寸post

-(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或更小)時就有問題了,是否是以爲後面的圖片太大了,this

而圖片的寬高又很差直接改,這時咱們就能夠先把圖片給作小點,在加上就OK了。url

  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];

相關文章
相關標籤/搜索