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