iphone UIbezierpath不规则图像裁剪

时间:2012-10-01 08:48:20

标签: iphone objective-c uiimage crop uibezierpath

为iPhone制作拼图益智游戏。

这里我必须裁剪图像,如下图所示

enter image description here

在谷歌搜索后,我开始知道uibezier路径是以不规则形状裁剪图像的最佳路径。

但我没有得到任何关于如何裁剪图像的代码或想法。

1 个答案:

答案 0 :(得分:10)

这将需要大量的试验和错误,我很快就这样做,只是为了让您了解如何使用Bezier Paths创建形状。下面是创建我快速创建的方形的示例代码

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

如果我有更多时间,我可以创建图像,但是这样做很快,因为没有太多时间。一旦你了解了点数,你就不会太难用了。创建这个形状需要花费大量的试验和错误,但是使用我提供的代码作为如何使用Bezier路径创建形状的基础。你需要创建更多的点才能最终得到你想要的形状。

我还建议您查看Apples开发人员指南,了解如何创建不规则形状

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

上面的方法将采用bezier路径和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];

快速从图像的左上角开始制作一个正方形。例如,如果你有一个正方形图像,你可以遍历图像的宽度和高度,使用上面的代码裁剪成单独的正方形并单独返回它们。创建拼图拼图要复杂得多,但希望这有帮助

相关问题