使用 CALayer 绘制加号 (+)

Draw a plus (+) sign using CALayer

我不擅长使用 CALayer,但我需要绘制一个加号 (+) 并且我不想使用图像,因为我想为绘图设置动画。有帮助吗?

如 luk2302 所说,使用 CAShapeLayer.

您可以将 CGPath 安装到 CAShapeLayer。您可以从任何 UIBezierPath 中得到一个 CGPath。 (它有一个 CGPath 属性 可以让你获得任何 UIBezierPath 的底层 CGPath 对象。)

我建议阅读 UIBezierPath。它有方法 moveToPointaddLineToPoint.

您将移动到加号的顶部,向下添加一行,然后移动到加号的左侧并添加一条横线。

请注意,您还可以为图像制作动画,具体取决于您想要的动画类型。你需要做什么样的动画?

另一种简单的方法是使用两个具有相同背景颜色的 UIView,并将它们作为子视图添加到另一个 UIView。然后你可以使用 UIView animateWithDuration:... 方法来做你的简单动画。

在所有的反对票之后,我能够自己做。以下是其他可能需要此内容的方法

CGFloat height = 2.f;
CGFloat width = 3.f;
CGFloat cornerRadius =  1.f;

CALayer *hLayer = [CALayer layer];//this is the left - right stroke 
hLayer.frame = CGRectMake(0, CGRectGetMidY(self.bounds)-(height/2), width, height);
hLayer.cornerRadius = cornerRadius;

CALayer *vLayer = [CALayer layer];// this is the top - bottom stroke
vLayer.frame = CGRectMake(CGRectGetMidX(self.bounds) - (height/2), -3,height, width);
vLayer.cornerRadius = cornerRadius;

[self.layer addSublayer:hLayer];
[self.layer addSublayer:vLayer];