2012-10-01 60 views
9

我正在爲iPhone創建拼圖遊戲。iphone UIbezierpath不規則圖像裁剪

在這裏,我要裁剪圖像,就像下面的圖片

enter image description here

我才知道uibezier路徑是在不規則形狀裁剪圖像的優秀企業之一的谷歌搜索後。

但我沒有得到任何代碼或想法如何裁剪像上面的圖像。

+0

看看我的答案在這裏 http://stackoverflow.com/questions/13153223/how-to-crop-the-image-using-uibezierpath/ 15353848#15353848 –

回答

8

這將需要大量的試驗和錯誤,我很快就做到了這一點,只是爲了讓您瞭解如何使用貝塞爾路徑創建形狀。下面是示例代碼來創建我快速創建

UIBezierPath *aPath = [UIBezierPath bezierPath]; 

    // Set the starting point of the shape. 
    [aPath moveToPoint:CGPointMake(50.0, 50.0)]; 
    // Draw the lines. 
    [aPath addLineToPoint:CGPointMake(100.0, 50.0)]; 
    [aPath addLineToPoint:CGPointMake(100.0, 100.0)]; 
    [aPath addLineToPoint:CGPointMake(50.0, 100.0)]; 
    [aPath closePath]; 

    CAShapeLayer *square = [CAShapeLayer layer]; 
    square.path = aPath.CGPath; 
    [self.view.layer addSublayer:square]; 

如果我有更多的時間,我可以創造的形象,但這樣做快沒有太多的時間爲正方形。一旦你讓你的腦袋變得圓滿如何,它不難用。創建此形狀需要大量試驗和錯誤,但使用我提供的代碼作爲如何使用貝塞爾路徑創建形狀的基礎。您需要創建更多的點才能最終形成您想要的形狀。

我也建議在看蘋果開發者指南創建不規則形狀

http://developer.apple.com/library/ios/#documentation/2ddrawing/conceptual/drawingprintingios/BezierPaths/BezierPaths.html

。在「添加曲線到您的路徑」​​特別找了解如何創建曲線,並將其添加到您的形象。你需要的是,爲了創建拼圖塊的形狀,你要創建

編輯:

嘗試此方法

- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView; 
{ 
    if (![[imgView layer] mask]) 
     [[imgView layer] setMask:[CAShapeLayer layer]]; 

    [(CAShapeLayer*) [[imgView layer] mask] setPath:[clippingPath CGPath]]; 
} 

上述方法將採取貝塞爾路徑和ImageView的和然後將bezier路徑應用於該特定的imageView。它也會做剪輯。我會想要花費大量的嘗試和錯誤來設計恰當的形狀,有時候可能很困難並且很難製作複雜的形狀。應用此代碼

UIBezierPath *aPath = [UIBezierPath bezierPath]; 
    // Set the starting point of the shape. 
    [aPath moveToPoint:CGPointMake(0.0, 0.0)]; 
    // Draw the lines. 
    [aPath addLineToPoint:CGPointMake(50.0, 0.0)]; 
    [aPath addLineToPoint:CGPointMake(50.0, 50.0)]; 
    [aPath addLineToPoint:CGPointMake(0.0, 50.0)]; 
    [aPath closePath]; 

    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bar.png"]]; 
    imgView.frame = CGRectMake(0, 0, 100, 100); 
    [self setClippingPath:aPath :imgView]; 
    [self.view addSubview:imgView]; 

簡單的例子就迅速作出方形出的圖像的左上角部分。例如,如果你有一個正方形的圖像,你可以遍歷圖像的寬度和高度,使用上面的代碼剪切成單獨的正方形並單獨返回它們。創建拼圖塊很複雜,但希望這可以幫助

+0

非常感謝您的回覆,並花時間回答我的問題,這真的很可觀。是的,現在我清楚在哪條路上我應該旅行,在這裏我的另一個問題是裁剪圖像。你有什麼想法嗎?使用這個uibezier路徑繪製曲線繪製曲線? – nik

+0

我只是想匹配這種模式與uiimage,我只是想用該模式裁剪圖像 – nik

+1

看到我的編輯,我包括一個方法,你可以使用它將採取bezier路徑和imageView,併爲你做剪裁。希望這有助於 – AdamM