您的位置:首页 > 其它

Quartz2D使用(绘制基本图形)

2016-01-11 00:00 295 查看
摘要: 关于绘制基本图形难懂的概念问题

一 、基本概念

图形上下文(Graphics Context):是一个CGContextRef类型的数据

图形上下文的作用:保存绘图信息、绘图状态
只要上下文不同,绘制的地方就不同。

本文说明如何把图片绘制到Bitmap上面去,即要求生成一张图片,图片上面保存了绘图信息。

Bitmap就是图片,相当于系统的UIimage。一个UIImage就是一个Bitmap
二、补充说明:

1.创建Bitmap图形上下文的方法

//方法1 UIGraphicsBeginImageContext(<#CGSize size#>);

//方法2 UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)

使用两个方法同样都可以创建,但是使用第一个方法将来创建的图片清晰度和质量没有第二种方法的好。

方法2接收三个参数:

CGSize size:指定将来创建出来的bitmap的大小

BOOL opaque:设置透明YES代表透明,NO代表不透明

CGFloat scale:代表缩放,0代表不缩放

创建出来的bitmap就对应一个UIImage对象

三、代码实例

//
//  ViewController.m
//  savePictre
//
//  Created by emily on 16/1/8.
//  Copyright © 2016年 emily. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

}
//点击按钮事件
- (IBAction)btnClick:(UIButton *)sender {

// 加载要裁剪的图片
UIImage * image = [UIImage imageNamed:@"me"];

// 开启一个比图片稍大的图形上下文(bitmap)

CGFloat margin = 5;

CGSize ctxSize = CGSizeMake(image.size.width + 2 * margin, image.size.height + 2 * margin);

UIGraphicsBeginImageContextWithOptions(ctxSize, NO, 0.0);

//获取刚刚开启的图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();

/**绘制一个圆环*/
//确定圆心
CGPoint centerP = CGPointMake(ctxSize.width/2, ctxSize.height/2);

CGFloat radius = MIN(image.size.width, image.size.height)/2;

UIBezierPath * path1 = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];

CGContextAddPath(ctx, path1.CGPath);
//设置线宽和颜色
[[UIColor yellowColor]set];

CGContextSetLineWidth(ctx, 5);

//渲染
CGContextDrawPath(ctx, kCGPathStroke);
/**绘制一个要裁剪的圆形*/
UIBezierPath * path2 = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];

CGContextAddPath(ctx, path2.CGPath);

CGContextClip(ctx);
//绘制图片
[image drawAtPoint:CGPointMake(margin, margin)];

//从图形上下文中获取图片
UIImage * getImage = UIGraphicsGetImageFromCurrentImageContext();
//获得屏幕的缩放比
CGFloat scale = [UIScreen mainScreen].scale;
// 切割图片
CGFloat x = 0;
CGFloat y = (getImage.size.height - 2 * radius)/2;
CGFloat h =2 * radius ;
CGFloat w = 2 * radius;

x *= scale;
y *= scale;
h *= scale;
w *= scale;

CGImageRef imageRef = CGImageCreateWithImageInRect(getImage.CGImage, CGRectMake(x, y,w , h));

getImage = [UIImage imageWithCGImage:imageRef];
//释放
CGImageRelease(imageRef);
//关闭图形上下文
UIGraphicsEndImageContext();

//显示图片
self.imageView.image = getImage;

//保存相册
UIImageWriteToSavedPhotosAlbum(getImage, nil, nil, nil);

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


Emily.Wang
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: