What I have:
To create this line, I basically have an UIView
and I do the following:
void setLayerToLineFromAToB(CALayer *layer, CGPoint a, CGPoint b, CGFloat lineWidth)
{
CGPoint center = { 0.5 * (a.x + b.x), 0.5 * (a.y + b.y) };
CGFloat length = sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
CGFloat angle = atan2(a.y - b.y, a.x - b.x);
layer.position = center;
layer.bounds = (CGRect) { {0, 0}, { length + lineWidth, lineWidth } };
layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
}
Note: This code was found here on stackoverflow, so if someone can give me the reference to it I would appreciate.
What I want:
Ok so the "only" thing I need is to create this pattern on the UIView
. I know I am able to do this using Quartz2D (a simple way to do it can be found here). But I want to do it by manipulating the CALayer
and not going to to the draw method. Why? Because of the transformation I am making on my UIView
, I am not able to draw correctly using the draw
method.
Edit 1:
Just to illustrate my problem:
Normally what you have is UIView
and then you basically just draw something in it (in this case a simple line). The solution I found to get rid of the "gray" area, was to instead of drawing something, just transform the UIView
itself. It work well, if you want a fully filled line, the problem comes when you want a dashed one.
The accepted answer has a coordinate problem. The line will be drawn some distance below. And I cannot figure out why and how much distance it increases on Y coordinate.
There's a way to draw a dashed line with correct coordinate:
This answer is from Draw dotted (not dashed!) line, with IBDesignable in 2017. DON'T DON'T DON'T forget to set the background color as white when you want a black dashed line!! By default the view has a black background color, and the line color is also black, so I thought it was a solid line. It cost me half a day to find out. T_T
Swift 2.2
dropping this in here to save others time..
Note: The code from Prince did really help me out, so I will give him +10 for the tips. But in the end, I add to come with my own code. I will also add some context to it, so it can be useful for future readers
The final code was like this:
In my case, the beginPoint and endPoint are movable by the user, by using KVO. So when one of them moves:
I did play a lot with Prince's code. I tried on the
draw:
method, which add a thin line between the dashed line (a bit weird...) and I also tried oninitWithFrame:
. By itself his code, without any modifications, would give me this kind of errors on the console:Dash Line in Swift4 • Xcode 9
Crate a CAShapeLayer & use lineDashPattern
Usage:
Output:
First all the credit goes to RuiAAPeres and Prince, I'm just encapsulating their answers into a UIView object that others can drop into their projects and use
Here is Swift 3 version of Alexandre G's answer https://stackoverflow.com/a/38194152/1800489