【问题标题】:How to draw an open ended triangle with a specific angle in an UIView?如何在 UIView 中绘制具有特定角度的开放式三角形?
【发布时间】:2014-07-24 22:12:29
【问题描述】:

我被难住了,需要一些帮助。出于测试目的,我有一个通过 drawRect 绘制的 UIView(下面的代码)。我可以画一个特定角度的圆圈,但它是填充和闭合的。我需要它打开和抚摸。我目前正在使用 UIBezierPath 来执行此操作,但有更好的方法吗?我可以在 UIBezierPath 中绘制我想要的开放式三角形,但我无法指定我需要它的角度(下面的代码也是)。对此的任何帮助将不胜感激。谢谢。

下图是我希望它以特定角度绘制时的样子。

#import "AngleView.h"
#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * degrees)/ 180)
@implementation AngleView

-(void)drawRect:(CGRect)rect {

UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointZero
                                                     radius:50
                                                 startAngle:0
                                                   endAngle:DEGREES_TO_RADIANS(45)
                                                  clockwise:NO];

[aPath fill];
}

@end

这是我如何在没有特定角度的情况下绘制它。

UIBezierPath* bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint: CGPointMake(86.5, 33.5)];
[bezierPath addLineToPoint: CGPointMake(60.5, 62.5)];
[bezierPath addLineToPoint: CGPointMake(87.5, 62.5)];
[[UIColor blackColor] setStroke];
bezierPath.lineWidth = 1;
[bezierPath stroke];

【问题讨论】:

  • 你考虑过只画两条单独的线吗?
  • 是的,这就是我从一开始就想做的事情,但我认为这是错误的做法并放弃了这个想法,但我想我应该这样做吧?但是,这不会使角的角看起来没有连接并且不锐利吗?谢谢。

标签: ios objective-c drawrect uibezierpath


【解决方案1】:

您可以从同一点绘制两条独立的线,而不是尝试绘制一条线,您可以为其中一条线指定角度。

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, 119.5);  //here you can set originating point of line
    CGContextRotateCTM(context, -45 * M_PI / 180);  //Change Angle here -45
    UIBezierPath* bezierPath = UIBezierPath.bezierPath;
    [bezierPath moveToPoint: CGPointMake(0, 0)];
    [bezierPath addCurveToPoint: CGPointMake(39, 0) controlPoint1: CGPointMake(39, 0) controlPoint2: CGPointMake(39, 0)];
    [UIColor.blackColor setStroke];
    bezierPath.lineWidth = 1;
    [bezierPath stroke];
    CGContextRestoreGState(context);

    //Second UIBezierPath with 0 angle
    context = UIGraphicsGetCurrentContext();
    UIBezierPath* bezier2Path = UIBezierPath.bezierPath;
    [bezier2Path moveToPoint: CGPointMake(0, 119.5)];
    [bezier2Path addCurveToPoint: CGPointMake(38.5, 119.5) controlPoint1: CGPointMake(38.5, 119.5) controlPoint2: CGPointMake(38.5, 119.5)];
    [UIColor.blackColor setStroke];
    bezier2Path.lineWidth = 1;
    [bezier2Path stroke];
    CGContextRestoreGState(context);
}

【讨论】:

  • 所以我只需要正确绘制基线,因为我在您的代码中看不到它。非常感谢!
  • 是的,代码只是绘制了 -45 角线,您可以重复相同的代码以 0 角绘制第二条线。
  • 感谢 mohacs!我总是在学习新东西。我相信您的代码会帮助其他有类似问题的人。
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2016-09-08
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
相关资源
最近更新 更多