【问题标题】:Drawing to a view from a function从函数绘制到视图
【发布时间】:2012-06-01 16:26:43
【问题描述】:

我可以通过将以下内容放入 UIView 并将其连接到情节提要视图来绘制一条线。

- (void)drawRect:(CGRect)rect {
CGContextRef  context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 10, 50);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);

}

但是,我想做的是在按下按钮时画一条线。为此,我假设我需要将一些代码写入 IBAction。我的问题是我不能简单地将上面的代码放入 IBAction,因为它给了我一个错误。

- (IBAction)draw:(id)sender{
 //Place code here

}

我的问题是,如何在每次按下按钮时画一条线?

如何连接相似的代码来绘制不同的线条,当我按下按钮时会触发

【问题讨论】:

    标签: objective-c ios5 xcode4


    【解决方案1】:

    要在 UIView 上绘图,您必须将 UIView 子类化

    在.h中

       @MyCustomView : UIView {
        }
    
        @end
    

    在.m

    @implementation MyCustomView
    
    - (void) drawRect: (CGRect) rect
    {
            CGContextRef  context = UIGraphicsGetCurrentContext();
            CGContextSetLineWidth(context, 5.0);
            CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
            CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
            CGColorRef color = CGColorCreate(colorspace, components);
            CGContextSetStrokeColorWithColor(context, color);
            CGContextMoveToPoint(context, 0, 0);
            CGContextAddLineToPoint(context, 10, 50);
            CGContextStrokePath(context);
            CGColorSpaceRelease(colorspace);
            CGColorRelease(color);
        }
    

    在你的视图控制器中

    -(void)methodCallCustomView{
    
           } 
    
    - (IBAction)draw:(id)sender{
       [self methodCallCustomView];
        }
    

    【讨论】:

    • 我试过了,但它不起作用并给出以下错误:: CGContextSetLineWidth: invalid context 0x0
    • @user1209902 我修改了我的答案,子类 UIView,并从 ViewController 调用您的自定义 UIView
    【解决方案2】:

    所以你希望 drawRect: 方法在你按下按钮时被调用?如果是这样,将消息 setNeedsDisplay 发送到具有 drawRect: 代码的视图。

    【讨论】:

    • 对不起,我的描述不清楚。这不是我想要调用的 drawRect。我想调用一个包含相似但不同代码的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 2020-08-10
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多