我正在为 iPhone 创建一个拼图游戏。
这里我必须像下图一样裁剪图像
在谷歌搜索之后,我开始知道 uibezier 路径是裁剪不规则形状图像的最佳路径。
但我没有得到任何代码或想法如何像上面那样裁剪图像。
最佳答案
这需要大量的试验和错误,我很快就这样做了,只是为了让您了解如何使用贝塞尔路径创建形状。下面是我快速创建的用于创建正方形的示例代码
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];
如果我有更多时间,我可以创建图像,但很快就完成了,因为没有太多时间。一旦你了解了这些点是如何产生的,它就不会太难使用。创建此形状需要大量试验和错误,但使用我提供的代码作为如何使用贝塞尔路径创建形状的基础。您将需要创建更多的点才能最终得到您想要的形状。
我还建议您查看有关创建不规则形状的 Apple 开发人员指南
请特别查看“将曲线添加到您的路径”以了解如何创建曲线并将它们添加到您的图像中。您将需要它来创建您要创建的拼图 block 形状
编辑:
试试这个方法
- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView;
{
if (![[imgView layer] mask])
[[imgView layer] setMask:[CAShapeLayer layer]];
[(CAShapeLayer*) [[imgView layer] mask] setPath:[clippingPath CGPath]];
}
上述方法将采用贝塞尔曲线路径和 ImageView,然后将贝塞尔曲线路径应用于该特定 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];
只是快速地从图像的左上部分制作了一个正方形。例如,如果您有一个方形图像,您可以遍历图像的宽度和高度,使用上面的代码裁剪成单独的正方形并单独返回它们。创建拼图 block 要复杂得多,但希望这对您有所帮助
关于iphone UIbezierpath 不规则图像裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670051/