美文网首页iOS_UIkitiOS基础扩展iOS
iOS开发中设置圆角的几种方法

iOS开发中设置圆角的几种方法

作者: YotrolZ | 来源:发表于2015-08-16 13:09 被阅读22609次

方式一:设置layer相关的属性

  • 如果这样的设置的view很多,影响流畅性
网友图片
  • 情景一:使用代码设置
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"friendsRecommentIcon"]];
    
// 设置圆角的大小
imageView.layer.cornerRadius = 5;
[imageView.layer setMasksToBounds:YES];
  • 情景二:在xib中设置
    • 利用KVC设置,如下图:
设置 Key Path 展示效果

方式二:画

  • 性能高
  • 可以给UIImage添加一个分类UIImage+Extension
  • 分类中增加一个返回圆形图片的方法,扩展性强
#import <UIKit/UIKit.h>

@interface UIImage (Extension)

- (UIImage *)circleImage;

@end
#import "UIImage+Extension.h"

@implementation UIImage (Extension)

- (UIImage *)circleImage {

    // 开始图形上下文
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    
    // 获得图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 设置一个范围
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    // 根据一个rect创建一个椭圆
    CGContextAddEllipseInRect(ctx, rect);

    // 裁剪
    CGContextClip(ctx);
    
    // 将原照片画到图形上下文
    [self drawInRect:rect];
    
    // 从上下文上获取剪裁后的照片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

具体使用:

// 获得的就是一个圆形的图片
UIImage *placeHolder = [[UIImage imageNamed:@"defaultUserIcon"] circleImage];

相关文章

网友评论

本文标题:iOS开发中设置圆角的几种方法

本文链接:https://www.haomeiwen.com/subject/surmqttx.html