打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
iOS小知识点05

UIImageView添加圆角

在项目中提供的图片是矩形的,现要改成圆角图片,于是找了一些资料,下面是添加圆角图片的方法
创建UIImage的分类UIImage+ImageRounderCorner
UIImage+ImageRounderCorner.h文件中

#import <UIKit/UIKit.h>@interface UIImage (ImageRounderCorner)/** 调用此方法,返回一个带有圆角的UIImage对象 *  参数一:圆角半径 *  参数二:图片的大小 */- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size;@end

UIImage+ImageRounderCorner.m文件中

#import "UIImage+ImageRounderCorner.h"@implementation UIImage (ImageRounderCorner)- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size {    CGRect rect = CGRectMake(0, 0, size.width, size.height);// 创建一个基于位图的上下文(context),并将其设置为当前上下文,size为新创建的位图上下文大小    // opaque 透明开关 // scale 缩放因子    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);    // 拿到当前上下文对象    CGContextRef ctx = UIGraphicsGetCurrentContext();    // 创建贝塞尔曲线    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];    // 添加路径    CGContextAddPath(ctx, path.CGPath);    // 裁剪    CGContextClip(ctx);    // 绘图    [self drawInRect:rect];    // 填充绘制    CGContextDrawPath(ctx, kCGPathFillStroke);    // 从当前位图上下文的内容输出一个UIImage图片    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    // 上下文栈pop出创建的context    UIGraphicsEndImageContext();    return newImage;}@end

使用:
在控制器中导入 #import "UIImage+ImageRounderCorner.h"

- (void)viewDidLoad {    [super viewDidLoad];    UIImage *image = [UIImage imageNamed:@"image"];    UIImage *cornerImage = [image imageAddCornerWithRadius: 50.0 andSize:CGSizeMake(50.0, 50.0)];    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];    [self.view addSubview:imageView];}

运行后,发现,将原有的矩形图片转换为了带圆角的图片。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
iOS实现圆形头像
iOS 高效添加圆角效果实战讲解
iOS开发UI篇—Quartz2D使用(图形上下文栈)
iOS开发中使用Quartz2D绘制上下文栈和矩阵的方法
IOS UIImageView
– (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCap
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服