UIView子类:未调用drawRect

时间:2012-03-31 14:06:47

标签: ios objective-c uiview

我是iOS编程的初学者,很抱歉,如果我的问题是一个愚蠢的问题。

我正在尝试创建一个在加载的图像上执行自定义绘图的应用程序。

为此,我发现解决方案是继承UIView并编辑drawRect方法。

我在以下代码上创建了该代码,该代码在链接到Interface Builder故事板文件中的按钮的IBAction上激活。

UIImageView *image = [[UIImageView alloc] initWithImage: [UIImage imageNamed:     @"SampleImage.jpg"]]; 
image.frame = previewView.frame;
[image setContentMode:UIViewContentModeScaleAspectFit];       

[previewView addSubview:image];

customView *aCustomView = [[customView alloc] initWithFrame: CGRectMake(image.bounds.origin.x, image.bounds.origin.y, image.bounds.size.width, image.bounds.size.height)];
[previewView addSubview:aCustomView];

customView是我创建的UIView子类,其initdrawRect方法设置如下:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    NSLog(@"INITIALIZING");
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    NSLog(@"DRAWING");

    CGContextClearRect(ctx, rect);

    CGContextSetRGBFillColor(ctx, 0, 255, 0, 0.3);
    CGContextFillEllipseInRect(ctx, rect); 

    CGContextSetRGBStrokeColor(ctx, 255, 0, 0, 1);
    CGContextSetLineWidth(ctx, 2);
    CGContextStrokeEllipseInRect(ctx, rect);
}

我遇到的问题是没有绘图,而NSLog我有“INITIALIZING”消息,但不是“DRAWING”绘图。

所以基本上它会产生initWithFrame,但它不会调用drawRect方法。

请你指点我做错了什么?

4 个答案:

答案 0 :(得分:16)

  1. 确保您的新视图类是UIView的子类,而不是UIImageView。
  2. 要确保新视图显示,您需要执行 [viewContainer addSubView:] 以调用drawRect。
  3. 来自文档的参考:

      

    优化UIImageView类以将其图像绘制到显示器。 UIImageView不会调用drawRect:一个子类。如果您的子类需要自定义绘图代码,建议您使用UIView作为基类。

    https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIImageView_Class/Reference/Reference.html

答案 1 :(得分:7)

保罗,

以下是您可以尝试的一些事项:

  1. initWithFrame中,检查frame变量是否包含您的内容 期望它: NSLog(@"Frame: %@", NSStringFromCGRect(frame));
  2. 将其添加到超级视图后尝试调用[preview setNeedsDisplay];
  3. 最后,我会改变

      

    image.frame = previewView.frame;

    使用:

      

    image.bounds = CGRectMake(0,0,previewView.frame.size.width,   previewView.frame.size.height);

答案 2 :(得分:3)

可能问题是aCustomView的框架是(0,0,0,0) 您可以尝试传递一个常量CGRect参数,如下所示:CGRectMake(5, 5, 100, 100)。

答案 3 :(得分:0)

在我的案例中的答案与我为类似问题阅读过的所有答案不同,也许会对其他人有所帮助。事实证明,在我的故事板上,“从目标继承模块”未选中,而同时模块为无。我添加了复选标记,下次运行应用程序时会调用 draw 方法。

相关问题