我们绘制UI界面的时候,一般我们做边框是用layer,然后再给它上面添加阴影什么的,我比较喜欢用下面这个方法,
UI弄几张边框的图片,用代码给图片拉伸
- (UIImage *)changeBorderImage:(UIImage *)borderImage { UIImage *image = borderImage; CGFloat top = 2; // 顶端盖高度 CGFloat bottom = 2 ; // 底端盖高度 CGFloat left = 2; // 左端盖宽度 CGFloat right = 2; // 右端盖宽度 UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right); // 指定为拉伸模式,伸缩后重新赋值 image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch]; return image; }
自定义一个边框视图或者在你的视图下面添加一个带有拉伸后的UIImage的UIImageView就行了
全部代码:
BorderView.h
// // BorderView.h // border_creat // // Created by 谭启宏 on 15/12/15. // Copyright © 2015年 谭启宏. All rights reserved. // #import <UIKit/UIKit.h> @interface BorderView : UIImageView @property (nonatomic,strong)UIImage *borderImage; - (instancetype)initWithFrame:(CGRect)frame borderImage:(UIImage *)borderImage; @end
BorderView.m
// // BorderView.m // border_creat // // Created by 谭启宏 on 15/12/15. // Copyright © 2015年 谭启宏. All rights reserved. // #import "BorderView.h" @implementation BorderView - (instancetype)initWithFrame:(CGRect)frame borderImage:(UIImage *)borderImage { self =[super initWithFrame:frame]; if (self) { self.image = [self changeBorderImage:borderImage]; } return self; } - (void)setBorderImage:(UIImage *)borderImage { self.borderImage = [self changeBorderImage:borderImage]; } - (UIImage *)changeBorderImage:(UIImage *)borderImage { UIImage *image = borderImage; CGFloat top = 2; // 顶端盖高度 CGFloat bottom = 2 ; // 底端盖高度 CGFloat left = 2; // 左端盖宽度 CGFloat right = 2; // 右端盖宽度 UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right); // 指定为拉伸模式,伸缩后重新赋值 image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch]; return image; } @end
ViewController.m
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; BorderView *borderView = [[BorderView alloc]initWithFrame:CGRectMake(100, 100, 100, 50) borderImage:[UIImage imageNamed:@"tool_biankuang2"]]; [self.view addSubview:borderView]; BorderView *borderView1 = [[BorderView alloc]initWithFrame:CGRectMake(100, 200, 150, 100) borderImage:[UIImage imageNamed:@"tool_biankuang2"]]; [self.view addSubview:borderView1]; BorderView *borderView2 = [[BorderView alloc]initWithFrame:CGRectMake(100, 350, 30, 100) borderImage:[UIImage imageNamed:@"tool_biankuang"]]; [self.view addSubview:borderView2]; }
效果图:
demo地址:http://pan.baidu.com/s/1dEpedBr
tips:图片只需要上下左右距离边部有几象数,中间空一部分就行了