[英]Drawing a line in iPhone / iPad
我想開發一個應用程序,當用戶可以繪制線條...但我不想繪制直線,但希望在用戶繪制它時顯示該行。 當用戶從A點到達BI時,想要整理線(如果用戶想要這樣)。
為了能夠做到這一點,我想將我的視圖改為從0,0(左上角)到320,480(對於iPhone)和768,1024(對於iPad)(右下)的網格。
對於這個問題,我的A點在10,10點,B點在100,100點。
我的問題:
- 如何創建此網格?
- 我如何創建這些點?
- 如何在不拉直的情況下畫出這條線?
- 如何繪制拉直線?
我的問題是我熟悉創建“普通”UI應用程序。 我不熟悉Open-GL等。
我希望有人可以幫助我。
最好的祝福,
保羅佩倫
你- (void)drawRect:(CGRect)rect
你的UIView
並覆蓋- (void)drawRect:(CGRect)rect
方法。
在那里你抓住圖形上下文:
CGContextRef context = UIGraphicsGetCurrentContext();
並使用它來進行Core Graphics調用,例如:
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);
查看Quartz 2D Programming Guide了解所有細節。
當用戶根據起點和終點拖動它時,您可以拖動直線使用UIBezierPath和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];
}
希望這有助於實現您的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.