在我的自定义视图中绘图

时间:2012-08-22 05:02:10

标签: iphone objective-c xcode drawing

我添加了一个自定义视图,并希望绘制一个内部较小的圆,外部较大的圆和垂直线。我班上的drawRect:方法看起来像这样。

- (void) drawRect:(CGRect)rect{
    CGContextRef myContext = UIGraphicsGetCurrentContext();
    float height = rect.size.height;
    float width = rect.size.width;
    CGContextTranslateCTM(myContext, 0.0, height);
    CGContextScaleCTM(myContext, 1.0, -1.0);
    CGPoint middle = CGPointMake(width/2, height/2);
    UIBezierPath *innerCirclePath = [UIBezierPath bezierPathWithArcCenter:middle radius:25 startAngle:0 endAngle:DEGREES_TO_RADIANS(360) clockwise:YES];
    [innerCirclePath setLineWidth:2];
    [[UIColor redColor] setStroke];
    [innerCirclePath stroke];
    UIBezierPath *outerCirclePath = [UIBezierPath bezierPathWithArcCenter:middle radius:120 startAngle:0 endAngle:DEGREES_TO_RADIANS(360) clockwise:NO];
    [outerCirclePath setLineWidth:2];
    [[UIColor greenColor] setStroke];
    [outerCirclePath stroke];
    UIBezierPath *xAxis = [UIBezierPath bezierPath];
    [xAxis moveToPoint:CGPointMake(width, height/2 - 150)];
    [xAxis addLineToPoint:CGPointMake(width, height/2 + 150)];
    [xAxis closePath];
    [[UIColor grayColor] setStroke];
    [xAxis setLineWidth:2];
    [xAxis stroke];
}

现在我确实得到了外圈和内圈,但没有我想要的垂直线。它为什么不被画出来?

3 个答案:

答案 0 :(得分:1)

您正在使用这两行来设置“垂直线”的路径:

[xAxis moveToPoint:CGPointMake(width, height/2 - 150)];
[xAxis addLineToPoint:CGPointMake(width, height/2 + 150)];

问题是两个点的X坐标都是视图的右边缘。也许你希望它成为你观点的中心:

CGFloat xMid = CGRectGetMidX(rect);
[xAxis moveToPoint:CGPointMake(xMid, height/2 - 150)];
[xAxis addLineToPoint:CGPointMake(xMid, height/2 + 150)];

答案 1 :(得分:0)

您的视图背景是什么颜色?你应该确保它不会太接近greyColor,否则即使存在它也不会看到它。

答案 2 :(得分:0)

尝试改变这两行

[xAxis setLineWidth:2];
[[UIColor grayColor] setStroke];