【问题标题】:iPhone clip image with path带有路径的 iPhone 剪辑图像
【发布时间】:2024-01-10 10:09:01
【问题描述】:

我想用路径剪辑图像。在《使用 Quartz 编程》一书中,有一个关于如何绘制由矩形路径裁剪的圆的示例(第 37 页),还有一章关于使用现有图像作为模板进行图像遮罩(第 10 章)。但我仍然不确定如何使用路径剪辑现有图像。有没有例子或指针?

【问题讨论】:

    标签: iphone quartz-graphics


    【解决方案1】:

    这是一个应该可以工作的示例,它将剪切区域设置为路径(在我的例子中,这条路径是一个椭圆,你可以使用一个矩形)。然后绘制将被剪裁的图像。方法 drawRect: 是在我的例子中绘制 UIView 上下文的方法。

    
    - (void)drawRect:(CGRect)rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGMutablePathRef path = CGPathCreateMutable();
    //or for e.g. CGPathAddRect(path, NULL, CGRectInset([self bounds], 10, 20));
        CGPathAddEllipseInRect(path, NULL, [self bounds]);
        CGContextAddPath(context, path);
        CGContextClip(context);
        CGPathRelease(path);
        [[UIImage imageNamed:@"GC.png"] drawInRect:[self bounds]];
    }
    

    【讨论】:

    • 另一个问题:如何在不同的区域剪辑?我尝试在那里使用 CGAffineTransform 而不是 NULL 。但我最终使图像相对于视图偏离中心。
    • 顺便说一句,查看文档说 drawInRect 应该根据需要缩放图像。在我的代码中,它似乎没有按比例缩放(尽管这是我想要的)。但我想要几个不同区域的 UIView。