前面已經介紹過一種給UI控件設置圓角的方法了豆瘫,今天給大家介紹一種性能更加優(yōu)化的為圖片設置圓角的方法
Xib中設置控件的圓角铅乡、邊框效果
當我們在項目中顯示圖片的時候夏漱,如果想要將正方形的圖片轉換為原型圖片的話,如果使用layer進行設置有時就會有一點點卡(特別是在tableView中進行顯示的時候)
- 通常的解決的辦法就是通過Quartz2D將圖形繪制出一張圓形圖片來進行顯示霉囚。
1.創(chuàng)建UIImage的分類實現圓角方法
#import <UIKit/UIKit.h>
@interface UIImage (ZZYCircleImage)
- (UIImage *)circleImage;
@end
#import "UIImage+ZZYCircleImage.h"
@implementation UIImage (ZZYCircleImage)
- (UIImage *)circleImage
{
//1.開啟圖片圖形上下文:注意設置透明度為非透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
//2.開啟圖形上下文
CGContextRef ref = UIGraphicsGetCurrentContext();
//3.繪制圓形區(qū)域(此處根據寬度來設置)
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.width);
CGContextAddEllipseInRect(ref, rect);
//4.裁剪繪圖區(qū)域
CGContextClip(ref);
//5.繪制圖片
[self drawInRect:rect];
//6.獲取圖片
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//7.關閉圖形上下文
UIGraphicsEndImageContext();
return image;
}
@end
2.擴展——SDWebImage的簡單封裝
#import <UIKit/UIKit.h>
@interface UIImageView (ZZYImageView)
- (void)setCircleImage:(NSString *)imageUrl withPlaceholderImage:(NSString *)placeholderImageName;
@end
#import "UIImageView+ZZYImageView.h"
#import <UIImageView+WebCache.h>
#import "UIImage+ZZYCircleImage.h"
@implementation UIImageView (ZZYImageView)
- (void)setCircleImage:(NSString *)imageUrl withPlaceholderImage:(NSString *)placeholderImageName
{
UIImage * placeholderImage = [UIImage imageNamed:placeholderImageName];
[self sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
self.image = image ? [image circleImage]:[placeholderImage circleImage];
}];
}
@end