Drawing a line in iPhone / iPad

2020-02-09 11:43发布

I would like to develop an app when the user can draw lines... but I do not want to draw straight lines but want to show the line as the users draws it. When the user gets from point A to B I would like to straighten the line (if the users wants this).

To be able to do this I want to change my view into a grid starting at 0,0 (top left) and ending at 320,480 (for iPhone) and 768,1024 (for iPad) (bottom right).

For this question I have point A at 10,10 and point B at 100,100.

My question:
- How do I create this grid?
- How do I create these points?
- How do I draw this line without straightening it?
- How do I draw the straighten line?

My problem is that I am familiar with creating "normal" UI apps. I am not familiar with Open-GL ect.

I hope someone can help me with this.

Best regards,
Paul Peelen

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-09 11:57

You can drag straight line when user drag it based on starting and ending point draw a line using UIBezierPath and CAShapeLayer:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    startingPoint = [touch locationInView:baseHolderView];

}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    endingPoint = [touch locationInView:baseHolderView];
    [self makeLineLayer:baseHolderView.layer lineFromPointA:startingPoint toPointB:endingPoint];
}

-(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 = 2.0;
    line.strokeColor = [UIColor blackColor].CGColor;
    [layer addSublayer:line];
}

Hope this will help to achieve your goal.

查看更多
Luminary・发光体
3楼-- · 2020-02-09 12:08

You subclass your UIView and override the - (void)drawRect:(CGRect)rect method.

In there you grab a graphics context:

CGContextRef context = UIGraphicsGetCurrentContext();

And you use that to make Core Graphics calls, like:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath (context);
for (k = 0; k < count; k += 2) {
    CGContextMoveToPoint(context, s[k].x, s[k].y);
    CGContextAddLineToPoint(context, s[k+1].x, s[k+1].y);
}
CGContextStrokePath(context);

Look up the Quartz 2D Programming Guide for all the details.

查看更多
登录 后发表回答