Нарисуйте линию с CALayer
Я пытаюсь сделать линию между двумя точками, используя CALayer. Вот мой код:
//positions a CALayer to be a line between a parent node and its subnodes.
-(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB{
NSLog([NSString stringWithFormat:@"Coordinates: \n Ax: %f Ay: %f Bx: %f By: %f", pointA.x,pointA.y,pointB.x,pointB.y]);
//find the length of the line:
CGFloat length = sqrt((pointA.x - pointB.x) * (pointA.x - pointB.x) + (pointA.y - pointB.y) * (pointA.y - pointB.y));
layer.frame = CGRectMake(0, 0, 1, length);
//calculate and set the layer center:
CGPoint center = CGPointMake((pointA.x+pointB.x)/2, (pointA.y+pointB.y)/2);
layer.position = center;
//calculate the angle of the line and set the layer transform to match it.
CGFloat angle = atan2f(pointB.y - pointA.y, pointB.x - pointA.x);
layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
}
Я знаю, что длина вычисляется правильно, и я уверен, что центр тоже. Когда я запускаю его, отображаются строки, которые имеют правильную длину и проходят через центральную точку между двумя точками, но не вращаются правильно. Сначала я подумал, что линия вращается вокруг неправильной точки привязки, поэтому я сделал: layer.anchorPoint = center;
, но этот код не показывает никаких строк на экране. Что я делаю не так
Ответы
Ответ 1
Попробуй это...
-(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB
{
CAShapeLayer *line = [CAShapeLayer layer];
UIBezierPath *linePath=[UIBezierPath bezierPath];
[linePath moveToPoint: pointA];
[linePath addLineToPoint:pointB];
line.path=linePath.CGPath;
line.fillColor = nil;
line.opacity = 1.0;
line.strokeColor = [UIColor redColor].CGColor;
[layer addSublayer:line];
}
Ответ 2
Здесь версия Swift, основанная на Rajesh Choudhary, отвечает:
Swift 2
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.moveToPoint(start)
linePath.addLineToPoint(end)
line.path = linePath.CGPath
line.fillColor = nil
line.opacity = 1.0
line.strokeColor = UIColor.redColor().CGColor
layer.addSublayer(line)
}
Swift 3
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.fillColor = nil
line.opacity = 1.0
line.strokeColor = UIColor.red.cgColor
layer.addSublayer(line)
}
Ответ 3
Здесь версия Swift 3, основанная на Rajesh Choudhary, отвечает:
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.fillColor = nil
line.opacity = 1.0
line.strokeColor = UIColor.green.cgColor
layer.addSublayer(line)
}