nik*_*nik 9 iphone crop objective-c uiimage uibezierpath
我正在为iPhone创建一个拼图益智游戏.
在这里,我必须像下图一样裁剪图像

谷歌搜索后,我开始知道uibezier路径是以不规则形状裁剪图像的最佳路径.
但我没有得到任何代码或想法如何裁剪像上面的图像.
Ada*_*amM 11
这将需要大量的试验和错误,我很快就这样做,只是为了让您了解如何使用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];
Run Code Online (Sandbox Code Playgroud)
如果我有更多的时间,我可以创建图像,但这样做很快,因为没有太多时间.一旦你了解了点数,你就不会太难用了.创建这个形状需要花费大量的试验和错误,但是使用我提供的代码作为如何使用Bezier路径创建形状的基础.您需要创建更多的点才能最终得到您想要的形状.
我还建议您查看Apples开发人员指南,了解如何创建不规则形状
特别要注意"将曲线添加到路径中",以了解如何创建曲线并将其添加到图像中.您需要这样才能创建您正在尝试创建的拼图块形状
编辑:
试试这个方法
- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView;
{
if (![[imgView layer] mask])
[[imgView layer] setMask:[CAShapeLayer layer]];
[(CAShapeLayer*) [[imgView layer] mask] setPath:[clippingPath CGPath]];
}
Run Code Online (Sandbox Code Playgroud)
上面的方法将采用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];
Run Code Online (Sandbox Code Playgroud)
刚刚从图像的左上角快速制作了一个正方形.例如,如果你有一个正方形图像,你可以遍历图像的宽度和高度,使用上面的代码裁剪成单独的正方形并单独返回它们.创建拼图拼图要复杂得多,但希望这会有所帮助