iOS设置圆形(圆角)UIView、UIButton的简单方法

来源:互联网 发布:windows hadoop2.7.3 编辑:程序博客网 时间:2024/06/05 01:42

有时候需要快速的创建一些圆形的UIView,UIButton之类的,如果有时间自己封装控件,使用CG绘制当然很好,但是如果没有时间,那么就使用CALayer的特性来做吧。

  UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];   //只需要设置layer层的两个属性   //设置圆角    imageView.layer.cornerRadius = imageView.frame.size.width / 2;   //将多余的部分切掉    imageView.layer.masksToBounds = YES;    [self.view addSubview:imageView];


----------------------------------------------------------------------------------------------------------------------------------------------------------------

 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];    imageView.image = [UIImage imageNamed:@"1"];    //开始对imageView进行画图    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);    //使用贝塞尔曲线画出一个圆形图    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];    [imageView drawRect:imageView.bounds];    imageView.image = UIGraphicsGetImageFromCurrentImageContext();     //结束画图    UIGraphicsEndImageContext();    [self.view addSubview:imageView];
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

第三种方法,性能最好写,记得导入<AVFoundation/AVFoundation.h>

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];    imageView.image = [UIImage imageNamed:@"1"];    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];    //设置大小    maskLayer.frame = imageView.bounds;    //设置图形样子    maskLayer.path = maskPath.CGPath;    imageView.layer.mask = maskLayer;    [self.view addSubview:imageView];}

这三种方法中第三种最好,对内存的消耗最少啊,而且渲染快速。

 iOS

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发个红包



0 0
原创粉丝点击