Iphone 在objective c IOS5中的viewcontroller类中单击按钮时绘制矩形

Iphone 在objective c IOS5中的viewcontroller类中单击按钮时绘制矩形,iphone,objective-c,ios5,xcode4.3,Iphone,Objective C,Ios5,Xcode4.3,简单地说,我是在ipad上开发的初学者,当我点击或触摸按钮时,我需要在点x,y处绘制宽度和高度的矩形 我在谷歌上搜索过,但在按钮处理程序中找不到任何可以工作的东西。实际上,你需要用state来完成这项工作。只有一个地方允许你画画,那就是drawRect:。因此,当用户单击该按钮时,您需要设置一些实例变量,如\u isShowingRectangle或其他什么,然后在进行绘图的自定义UI视图上调用setNeedsDisplay 然后,在自定义视图的drawRect:中,可以检查是否设置了该状态变量

简单地说,我是在ipad上开发的初学者,当我点击或触摸按钮时,我需要在点x,y处绘制宽度和高度的矩形


我在谷歌上搜索过,但在按钮处理程序中找不到任何可以工作的东西。实际上,你需要用state来完成这项工作。只有一个地方允许你画画,那就是
drawRect:
。因此,当用户单击该按钮时,您需要设置一些实例变量,如
\u isShowingRectangle
或其他什么,然后在进行绘图的自定义UI视图上调用
setNeedsDisplay

然后,在自定义视图的
drawRect:
中,可以检查是否设置了该状态变量,并绘制(或不绘制)矩形。绘制代码取决于您使用的图形层,但它可能类似于

CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(ctxt,[[UIColor blackColor] CGColor]);
CGContextSetLineWidth(ctxt,3.0);
CGContextStrokeRect(ctxt,CGRectMake(10,20,100,50));

在viewDidLoad方法中创建矩形按钮,并在ViewController.m中写入
-(void)rectangleButtonSelected
方法。还可以创建UIView的类
RectangleView

-(void)rectangleButtonSelected{

    RectangleView *temp = [[RectangleView alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];

    temp.center = CGPointMake(arc4random()%100, arc4random()%200);
    NSLog(@"The Main center Point : %f  %f",temp.center.x,temp.center.y);

    [self.view addSubview:temp];

}
在RectanglerView.m中实现
-(void)drawRect:(CGRect)rect
方法

- (void)drawRect:(CGRect)rect
{

    // Drawing code

    context =UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
    // And draw with a blue fill color
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0);


    CGContextAddRect(context, self.bounds);
    CGContextStrokePath(context);


    // Close the path
    CGContextClosePath(context);
    // Fill & stroke the path
    CGContextDrawPath(context, kCGPathFillStroke);
}

我希望它将对您有所帮助

这意味着我需要创建一个新类作为UIview,并将custum类设置为新类好的,我如何在这2个类和SETNEEDS之间连接显示你能给我举个例子吗我知道绘图的代码,但我的问题是代码或调用绘图函数真的非常感谢我花了5个小时的时间尝试祝你好运