2010-04-18 75 views
1

我最近问了一个关于在视图的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并将原点设置为不同的位置,但同时扩大矩形的大小?

当我画一个更大的矩形比通过视图显示时,这会导致性能损失吗?

回答

1

听起来就像你已经想到了自己。 drawAtPoint是你应该使用的。 drawInRect将缩放图像以适应目标矩形,这在计算上更加昂贵。假设你的图像比你的视图大,你会传递负的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]; 

}