iOS Quartz2D裁剪图片

1. 对上面的图片做裁剪:

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 画圆

    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 60, 60));

    // 圆外的都剪掉

    CGContextClip(ctx);

    CGContextFillPath(ctx);

    

    // 画图

    UIImage *image = [UIImage imageNamed:@"123"];

    [image drawAtPoint:CGPointMake(15, 15)];

 

2. 模拟器运行结果:

3. 再画一条线,要求不要裁剪线:

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 画圆

    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 60, 60));

    // 圆外的都剪掉

    CGContextClip(ctx);

    CGContextFillPath(ctx);

    // 画图

    UIImage *image = [UIImage imageNamed:@"123"];

    [image drawAtPoint:CGPointMake(15, 15)];

    // 画线

    CGContextSetLineWidth(ctx, 10);

    CGContextMoveToPoint(ctx, 20, 80);

    CGContextAddLineToPoint(ctx, 120, 80);

    CGContextStrokePath(ctx);

4. 出现这种情况的原因:

UIView上有图层(图1,图2),Quartz2D的所有操作都是在图层上进行的,在图层上画一个圆(图3),然后做Clip,再画一条线(图4),实际得到结果会是图5的样子,因为圆外的区域都被剪掉了

5. 正确的做法是利用图形上下文栈:

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSaveGState(ctx);

    // 画圆

    CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 60, 60));

    // 圆外的都剪掉

    CGContextClip(ctx);

    CGContextFillPath(ctx);

    // 画图

    UIImage *image = [UIImage imageNamed:@"123"];

    [image drawAtPoint:CGPointMake(15, 15)];    

    CGContextRestoreGState(ctx);

    // 画线

    CGContextSetLineWidth(ctx, 10);

    CGContextMoveToPoint(ctx, 20, 80);

    CGContextAddLineToPoint(ctx, 120, 80);

    CGContextStrokePath(ctx);

 

posted @ 2015-03-23 16:15  oumygade  阅读(234)  评论(0编辑  收藏  举报