IOS view border Simple practices, ios view border
When we draw the UI interface, we usually use layer as the border, and then add a shadow or something to it. I prefer to use the following method,
The UI gets several border images and uses code to stretch the image.
-(UIImage *) changeBorderImage :( UIImage *) borderImage {UIImage * image = borderImage; CGFloat top = 2; // top cover height CGFloat bottom = 2; // bottom end cover height CGFloat left = 2; // left End Cover width CGFloat right = 2; // right End Cover width UIEdgeInsets insets = UIEdgeInsetsMake (top, left, bottom, right ); // specify the stretch mode. after scaling, assign image = [image resizableImageWithCapInsets: insets resizingMode: UIImageResizingModeStretch]; return image ;}
You can customize a border view or add a UIImageView with a stretched UIImage under your view.
All code:
BorderView. h
//// BorderView. h // border_creat /// Created by Tan qihong on 15/12/15. // Copyright©2015 tan qihong. 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 Tan qihong on 15/12/15. // Copyright©2015 tan qihong. 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; // top cover height CGFloat bottom = 2; // bottom end cover height CGFloat left = 2; // left End Cover width CGFloat right = 2; // width of the right end cover UIEdgeInsets insets = UIEdgeInsetsMake (top, left, bottom, right); // specify the stretch mode and assign the 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 address: http://pan.baidu.com/s/1dEpedBr
Tips