UIButton設置imgae圖片自適應button的大小且不變形


在某些情況下,我們使用的UIButton的背景圖片不一定就是標准的尺寸,有時會偏大,那么怎么辦?

這個比較簡單直接設置 :    self.imageView.contentMode = UIViewContentModeScaleAspectFill;

但是問題來了,如果圖片尺寸比較button的bounds 小的話,他不會撐滿整個控件默認會居中顯示,有些時候這並不是我們想要的效果。有時我們希望他能撐滿整個button。

 

1
- (CGRect)imageRectForContentRect:(CGRect)bounds{
2
        return CGRectMake(0.0, 0.0, self.size.width, self.size.height);
3
}

 

那么這樣處理即可:

繼承UIButton,重寫 imageRectForContentRect 方法返回button的bounds 

 

btn.imageView setContentMode:UIViewContentModeScaleAspectFill]; 

 

下面方法自己可以試下, 你就知效果了...

 

typedef NS_ENUM(NSInteger, UIViewContentMode) {

    UIViewContentModeScaleToFill,

    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent內容部分符合固定方面,其余內容是透明的

    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.內容擴充固定的方面,部分內容可能被剪

    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)范圍變化重繪

    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.內容保持相同大小定位調整

    UIViewContentModeTop,//貼頂

    UIViewContentModeBottom,//貼底

    UIViewContentModeLeft,//靠左

    UIViewContentModeRight,//靠右

    UIViewContentModeTopLeft,//左上

    UIViewContentModeTopRight,//右上

    UIViewContentModeBottomLeft,//左下

    UIViewContentModeBottomRight,//右下

};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM