【问题标题】:drawing rectangle on button click in viewcontroller class in objective c IOS5在目标c IOS5中的viewcontroller类中单击按钮上绘制矩形
【发布时间】:2012-05-10 04:55:19
【问题描述】:

我只是在 ipad 上开发的初学者,当我点击或触摸按钮时,我需要在 x,y 点绘制具有宽度和高度的矩形。

我在谷歌上搜索,但我没有发现按钮处理程序中有任何工作

【问题讨论】:

    标签: iphone objective-c ios5 xcode4.3


    【解决方案1】:

    在 viewDidLoad 方法中创建 rectangleButton 并在您的 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);
    }
    

    希望对你有帮助

    【讨论】:

    • 真的非常感谢,我花了 5 个小时努力让这个好运
    【解决方案2】:

    您实际上需要对状态执行此操作。只有一个地方可以让你画画,那就是drawRect:。因此,当用户单击按钮时,您需要设置一些实例变量,例如 _isShowingRectangle 或其他东西,然后在您正在绘制的自定义 UIView 上调用 setNeedsDisplay

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

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

    【讨论】:

    • 这意味着我需要创建新类作为 UIview 并将 custum 类设置为新的类我如何在这 2 个类和 setNeedsDisplay 之间连接你能给我举个例子我知道绘图代码但是我的问题是代码或调用绘图函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多