【问题标题】:Clipping different parts of an image with path使用路径剪切图像的不同部分
【发布时间】:2013-08-07 22:11:57
【问题描述】:

我最近问了一个关于在视图的 drawRect 方法中通过路径剪切图像的问题。

iPhone clip image with path

Krasnyk 的代码复制如下。

- (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]];
}

效果很好。但是,当我的图像大于视图本身时,如何显示图像的不同部分?

我尝试调整椭圆和/或 UIImage drawInRect 的位置(如上图所示)的平移,但发生了一些我无法解释的复杂效果(不需要的剪裁、奇怪的椭圆大小)。


编辑:也许我可以回答我自己的问题。我可以尝试 drawAtPoint 而不是 drawInRect 吗?还是drawInRect,将原点设置在不同的位置,但同时扩大矩形的大小?

当我绘制比视图显示的更大的矩形时,这是否会导致性能损失?

【问题讨论】:

    标签: iphone quartz-graphics


    【解决方案1】:

    听起来您已经自己想通了。 drawAtPoint 是您应该使用的。 drawInRect 将缩放图像以适合目标矩形,这在计算上更昂贵。假设您的图像大于您的视图,您将向 drawAtPoint 传递负 x 和 y 值,以剪切图像的内部部分。

    下面的示例应在您的视图中显示图像的中心部分:

    - (void)drawRect:(CGRect)rect {
       CGContextRef context = UIGraphicsGetCurrentContext();
       CGMutablePathRef path = CGPathCreateMutable();
       CGPathAddEllipseInRect(path, NULL, [self bounds]);
       CGContextAddPath(context, path);
       CGContextClip(context);
       CGPathRelease(path);
       UIImage *bigImage = [UIImage imageNamed:@"GC.png"];
       CGPoint topLeftOffset = CGPointMake((self.bounds.size.width - bigImage.size.width) / 2,(self.bounds.size.height - bigImage.size.height) / 2);
       [bigImage drawAtPoint: topLeftOffset];
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2011-10-15
      • 2017-06-04
      相关资源
      最近更新 更多