2010-04-18 78 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]; 

}