button 可以设置为图片,但是如果图片过小,那么不管 button 设置的 frame 大小是多少,都是显示的图片的大小,这样就需要用代码调整图片的大小。
UIImageView则不需要,因为图片会随着 imageview 的大小而变化。
如图所示,用的图片都是一个图片,设置的都是宽是屏幕大小,高200,从上到下一次为 button 的图片,button 使用放大后的图片,uiimageview 的图片
所以这里说明下怎么调整图片的大小,因为 image 自己不提供这个方法,所以另外写一个方法
【一】代码示例
自定义的类
.h文件:
#import <UIKit/UIKit.h> @interface UIImage(scale) -(UIImage*)scaleToSize:(CGSize)size; @end
.m文件
#import "ImageScale.h"@implementation UIImage(scale)
-(UIImage*)scaleToSize:(CGSize)size
{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return scaledImage;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/@end
调用和使用的方法
UIImage *images1=[UIImage imageNamed:@"img2.png"];
UIButton *button1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
[button1 setImage:images1 forState:UIControlStateNormal];
[self.view addSubview:button1];
UIImage *images=[UIImage imageNamed:@"img2.png"];
UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, 200)];
[button setImage:[images scaleToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 200)] forState:UIControlStateNormal];
[self.view addSubview:button];
UIImageView *views=[[UIImageView alloc]initWithFrame:CGRectMake(0, 500, [UIScreen mainScreen].bounds.size.width, 200)];
[views setImage:[UIImage imageNamed:@"img2.png"]];
[self.view addSubview:views];
【二】demo 下载
GitHub下载:https://github.com/DamonHu/HudongImageDemo
GitOsc下载:http://git.oschina.net/DamonHoo/HudongImageDemo
【三】参考文章
http://blog.csdn.net/ldd909/article/details/6570156
iOS UIImage扩展方法(category):放大、旋转、合并UIImage、增加渐变层、添加阴影、调节透明度
版权属于:胡东东博客
本文链接:http://blog.hudongdong.com/oc/146.html
自2017年12月26日起,『转载以及大段采集进行后续编辑』须注明本文标题和链接!否则禁止所有转载和采集行为!
☟☟如文章有用,可点击一次下方广告支持一下☟☟
我遇到了一个图片太大,导致btn的image被拉伸的问题,改了下btn的imageView的contentMode为aspectFit就能正常显示啦~~
是的,就是要么修改图片,要么修改图片的显示样式,这个写的老了,