如何在iPhone中的viewdidload方法中绘制Arc

时间:2011-12-02 06:05:26

标签: iphone xcode

我尝试在视图中绘制弧线,我使用此代码。

- (void)viewDidLoad
{

    [super viewDidLoad];

    CGRect rect = CGRectMake(0,0,340,480);  
    UIView *ui = [[UIView alloc] initWithFrame:rect];
    [self.view addSubview:ui];
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextAddArc(context, 50, 50, 20, 0, 30, 0); 
    //set the fill or stroke color
    CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1.0);
    CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);

    //fill or draw the path
    CGContextDrawPath(context, kCGPathStroke);
    CGContextDrawPath(context, kCGPathFill);
}

如果有可能在viewdidload方法中绘制弧,请指导我。

2 个答案:

答案 0 :(得分:6)

您的观点应该在请求时绘制(例如在drawRect:中),而不是在加载时您的视图控制器绘制。

所以你可能想要尝试的是创建一个UIView子类并将绘图代码移动到它的drawRect:

非常简短:

@interface MONView : UIView
@end

@implementation MONView

- (void)drawRect:(CGRect)frame
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    <-- now draw here -->

}

@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect rect = CGRectMake(0,0,340,480);
    UIView * ui = [[MONView alloc] initWithFrame:rect];
    [self.view addSubview:ui];
    [ui release];
}

答案 1 :(得分:5)

无法在视图中绘制圆弧。加载。

您需要做的是: -

1.)在项目中添加UIView类型的文件(例如ArcView.hArcView.m

2.)在ArcView.m文件实现- (void)drawRect:(CGRect)rect方法

3.)在这种方法中,您需要编写绘制弧形或绘制任何内容的逻辑

4.)现在,您必须显示弧线的ViewController可以说(ArcViewController是您要在其中显示弧线的文件)

5.)在ArcViewController.m文件中,您需要执行以下步骤: -

一个。)#import "ArcView.h"

b。)每当你想要显示你的弧视图时: -

ArcView *vw = [[ArcView alloc] initWithFrame:*your required frame where you want to show arc*];
vw.backgroundColor=[UIColor redColor];
[self.view addSubview:vw];
[vw release];

之后,您将看到屏幕上出现弧线。