如何在UIView中绘制一个具有特定角度的开口三角形?

时间:2014-07-24 22:12:29

标签: ios objective-c drawrect uibezierpath

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

下图是当我以特定角度绘制它时我想看的样子。

enter image description here

#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];

1 个答案:

答案 0 :(得分: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);
}