注:旋轉、平移、縮放,必須放在畫圖之前
平移:
<span style="font-size:18px;">// 獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 畫一個三角形
// 定義三個點
CGPoint point[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, point, 3);
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
#warning 旋轉、平移、縮放,都要放在畫圖之前
// 平移
CGContextTranslateCTM(context, 100, 0);
// 畫第二個三角形
// 定義三個點
CGPoint points[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, points, 3);
[[UIColor whiteColor] set];
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
</span>
效果:
旋轉:圍繞左上角(0,0)旋轉
// 獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 畫一個三角形
// 定義三個點
CGPoint point[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, point, 3);
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
// 旋轉
// 負數:逆時針
// 圍繞左上角(0,0)旋轉
CGContextRotateCTM(context, - M_PI * 0.125);
// 畫第二個三角形
// 定義三個點
CGPoint points[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, points, 3);
[[UIColor whiteColor] set];
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
效果:
縮放:
// 獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 畫一個三角形
// 定義三個點
CGPoint point[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, point, 3);
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
// 縮放
CGContextScaleCTM(context, 3, 4);
// 畫第二個三角形
// 定義三個點
CGPoint points[3] = {{50, 50}, {100, 80}, {10, 80}};
CGContextAddLines(context, points, 3);
[[UIColor whiteColor] set];
// 合併路徑
CGContextClosePath(context);
// 渲染
CGContextStrokePath(context);
效果:
裁剪圓形圖片:
// 獲取圖形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 設置圖片的rect
CGRect imageRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
// 在rect中畫一個內切圓
CGContextAddEllipseInRect(context, imageRect);
// 剪掉圓外面的部分
CGContextClip(context);
// 只把圖片顯示在UIView上
UIImage *image = [UIImage imageNamed:@"papa"];
[image drawInRect:imageRect];
// 添加一個圓形的邊框
// 設置邊框顏色
[[UIColor blueColor] set];
// 設置線寬
CGContextSetLineWidth(context, 5);
// 畫圓
CGContextAddEllipseInRect(context, imageRect);
// 渲染
CGContextStrokePath(context);
效果: