UIView子类:未调用drawRect

Dob*_*ode 14 objective-c uiview ios

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

我正在尝试制作一个在加载的图像上执行自定义绘图的应用程序.

为此,我发现解决方案是子类化UIView和编辑drawRect方法.

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

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];
Run Code Online (Sandbox Code Playgroud)

customViewUIView我创建的子类,其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);
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是没有绘图,而且NSLog我有"INITIALIZING"消息,但不是"DRAWING"绘图.

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

能不能指出我做错了什么?

Xin*_*ing 17

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

来自文档的参考:

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

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


mpr*_*vat 8

保罗,

您可以尝试以下几种方法:

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

最后,我会改变

image.frame = previewView.frame;

有:

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