通過CALayer給view設置邊框,邊框是往view內部填充。view系統自帶的layer,稱為根層
UIImageView顯示的圖片是放在UIImageView根層layer的contents里面的
//設置邊框
self.imageView.layer.borderColor = [UIColor blueColor].CGColor;
self.imageView.layer.borderWidth = 3;
//設置陰影
//陰影的不透明度0-1,1是不透明,0是透明
self.imageView.layer.shadowOpacity = 1;
//(陰影的偏移量)x為正,陰影在右邊,為負,陰影在左邊。y為正,陰影在下邊,為負,陰影在上面
self.imageView.layer.shadowOffset = CGSizeMake(-10, 10);
// 陰影的顏色
self.imageView.layer.shadowColor = [UIColor greenColor].CGColor;
//設置圓角
self.imageView.layer.cornerRadius = 50;
//超過根層以外的內容給裁剪掉,包括陰影也會被裁解掉
clipsToBounds操作的其實還是layer.masksToBounds
//self.imageView.clipsToBounds = YES;
//離屏渲染是masksToBounds造成的,不是cornerRadius造成的
self.imageView.layer.masksToBounds = YES;
// UIImageView顯示的圖片就放在layer的這個屬性中
NSLog(@"%@",self.imageView.layer.contents);
一般在tableView列表中,圖片有圓角的話,是不用clipsToBounds和masksToBounds來設置圖片圓角的,
因為會觸發離屏渲染,這是消耗性能的。而直接用Quartz2D來裁剪,因為這樣是不消耗性能的
裁剪圖片開啟的位圖上下文的大小,要跟圖片本身的大小保持一致,防止圖片被壓縮放大。要先設置裁剪區域,
在畫圖像。一定要先生成圖片,在關閉位圖上下文,先關閉位圖上下文,是拿不到圖片的
生成一張圓形的image圖片
生成帶邊框圖片的邏輯,淡紅圓是邊框需要的,藍色的圓是裁剪用的。裁剪用的圓不需要畫上去
生成帶邊框的圖片
生成一張帶有邊框的圓角圖片分類
#import <UIKit/UIKit.h>
@interface UIImage (image)
/**
* 返回一張帶有邊框的圖片
*
* @param borderW 邊框的寬度
* @param color 邊框的顏色
* @param image 要裁剪的圖片
*
* @return 裁剪好帶有邊框的圖片
*/
+ (UIImage *)imageWithBorderW:(CGFloat)borderW color:(UIColor *)color image:(UIImage *)image;
@end
#import "UIImage+image.h"
@implementation UIImage (image)
+ (UIImage *)imageWithBorderW:(CGFloat)borderW color:(UIColor *)color image:(UIImage *)image {
//1.先開啟一個圖片上下文 ,尺寸大小在原始圖片基礎上寬高都加上兩倍邊框寬度.
CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW);
UIGraphicsBeginImageContext(size);
//2.填充一個圓形路徑.這個圓形路徑大小,和上下文尺寸大小一樣.
//把大圓畫到上下文當中.
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
[color set];
[path fill];
//3.添加一個小圓,小圓,x,y從邊框寬度位置開始添加,寬高和原始圖片一樣大小.把小圓設為裁剪區域.
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
//把小圓設為裁剪區域.
[clipPath addClip];
//4.把圖片給繪制上去.
[image drawAtPoint:CGPointMake(borderW, borderW)];
//5.從上下文當中生成一張圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//6.關閉上下文
UIGraphicsEndImageContext();
return newImage;
}
@end