UIImageView添加圓角
在項目中提供的圖片是矩形的,現(xiàn)要改成圓角圖片,于是找了一些資料,下面是添加圓角圖片的方法 創(chuàng)建UIImage的分類UIImage+ImageRounderCorner 在UIImage+ImageRounderCorner.h 文件中
#import <UIKit/UIKit.h>
@interface UIImage (ImageRounderCorner)
/** 調(diào)用此方法,返回一個帶有圓角的UIImage對象
* 參數(shù)一:圓角半徑
* 參數(shù)二:圖片的大小
*/
- (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);
// 創(chuàng)建一個基于位圖的上下文(context),并將其設(shè)置為當前上下文,size為新創(chuàng)建的位圖上下文大小
// opaque 透明開關(guān) // scale 縮放因子
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
// 拿到當前上下文對象
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 創(chuàng)建貝塞爾曲線
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
// 添加路徑
CGContextAddPath(ctx, path.CGPath);
// 裁剪
CGContextClip(ctx);
// 繪圖
[self drawInRect:rect];
// 填充繪制
CGContextDrawPath(ctx, kCGPathFillStroke);
// 從當前位圖上下文的內(nèi)容輸出一個UIImage圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 上下文棧pop出創(chuàng)建的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];
}
運行后,發(fā)現(xiàn),將原有的矩形圖片轉(zhuǎn)換為了帶圓角的圖片。
|