標籤:ios
畫直線
//拿到當前畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.拼接圖形(路徑) // 設定線段寬度 CGContextSetLineWidth(ctx, 10); // 設定線段頭尾部的樣式 CGContextSetLineCap(ctx, kCGLineCapRound); // 設定線段轉折點的樣式 CGContextSetLineJoin(ctx, kCGLineJoinRound); // 設定顏色 CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1); // 設定一個起點 CGContextMoveToPoint(ctx, 10, 10); // 添加一條線段到(100, 100) CGContextAddLineToPoint(ctx, 100, 100); // 渲染一次 CGContextStrokePath(ctx);
畫三角形
// 1.獲得畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫三角形 CGContextMoveToPoint(ctx, 0, 0); CGContextAddLineToPoint(ctx, 100, 100); CGContextAddLineToPoint(ctx, 150, 80); // 關閉路徑(串連起點和最後一個點) CGContextClosePath(ctx); //設定顏色 CGContextSetRGBStrokeColor(ctx, 0, 1, 0, 1); // 3.繪製圖形 CGContextStrokePath(ctx);
畫矩形
// 1.獲得畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫矩形 CGContextAddRect(ctx, CGRectMake(10, 10, 150, 100)); // set : 同時設定為實心和空心顏色 // setStroke : 設定空心顏色 // setFill : 設定實心顏色 [[UIColor whiteColor] set];// CGContextSetRGBFillColor(ctx, 0, 0, 1, 1); // 3.繪製圖形 CGContextFillPath(ctx);
畫圓
// 1.獲得畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫圓 CGContextAddEllipseInRect(ctx, CGRectMake(50, 10, 100, 100)); CGContextSetLineWidth(ctx, 10); // 3.顯示所繪製的東西 CGContextStrokePath(ctx);
畫圓弧
// 1.獲得畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫圓弧 // x\y : 圓心 // radius : 半徑 // startAngle : 開始角度 // endAngle : 結束角度 // clockwise : 圓弧的伸展方向(0:順時針, 1:逆時針) CGContextAddArc(ctx, 100, 100, 50, M_PI_2, M_PI, 0); // 3.顯示所繪製的東西 CGContextFillPath(ctx);
畫圖片
UIImage *image = [UIImage imageNamed:@"me"]; // 2.畫圖片// [image drawAtPoint:CGPointMake(50, 50)];// [image drawInRect:CGRectMake(0, 0, 150, 150)]; [image drawAsPatternInRect:CGRectMake(0, 0, 200, 200)];
畫字串
// 1.獲得畫布 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫矩形 CGRect cubeRect = CGRectMake(50, 50, 100, 100); CGContextAddRect(ctx, cubeRect); // 3.顯示所繪製的東西 CGContextFillPath(ctx); // 4.畫文字 NSString *str = @"哈哈哈哈Good morning hello hi hi hi hi"; // [str drawAtPoint:CGPointZero withAttributes:nil]; NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; // NSForegroundColorAttributeName : 文字顏色 // NSFontAttributeName : 字型 attrs[NSForegroundColorAttributeName] = [UIColor redColor]; attrs[NSFontAttributeName] = [UIFont systemFontOfSize:50]; [str drawInRect:cubeRect withAttributes:attrs];
【iOS開發】Quartz2D的簡單使用