如何在iOS中用四个锚点绘制不规则矩形并填充颜色

4
我目前正在开发类似于“kresta app”的应用程序。首先我从相册中选择了图片,然后用户可以选择他想要在哪个区域应用百叶窗和遮阳帘。所以我想做的是有四个固定点,用户可以触摸并拖动这些点来选择区域。我使用以下代码实现了这个逻辑。
在“touches moved”方法中,我调用了这个方法。
 UIBezierPath *aPath = [UIBezierPath bezierPath];

// Set the starting point of the shape.
   [aPath moveToPoint:pinImageView1.center];
// Draw the lines.
[aPath addLineToPoint:pinImageView2.center];
[aPath addLineToPoint:pinImageView3.center];
[aPath addLineToPoint:pinImageView4.center];
[aPath closePath];

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

我的问题是每次都添加一个图层。我该如何实现这个逻辑?有没有办法删除之前的图层并更新新的图层?如果我的方法不正确,请建议其他实现此逻辑的方法。

1个回答

1
如果你将这个 CAShapeLayer 的引用保存在一个类属性中,那么你可以简单地不断更新它的 path 属性,它会自动更新你视图层上的子层。因此,只需要调用一次 addSublayer,将来只需随时更新这个 CAShapeLayerpath,就可以反映出屏幕上形状的变化覆盖在图像上。

@banu,你的方法在初始添加图层时是正确的,但对于后续的更新,你只需要更新路径,而不是创建一个新的CAShapeLayer。我也没有看到你指定填充颜色的地方(例如square.fillColor = [[UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:0.2] CGColor];或其他),请注意。 - Rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接