ios - UIView 子类 : drawRect not called

标签 ios objective-c uiview

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

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

为此,我发现一个解决方案是子类化 UIView 并编辑 drawRect 方法。

我在以下代码中创建了它,该代码在链接到 Interface Builder Storyboard文件中的按钮的 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 方法。

你能指出我做错了什么吗?

最佳答案

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

引用文档:

The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.

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

关于ios - UIView 子类 : drawRect not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956565/

相关文章:

ios - GameplayKit GKMeshGraph 障碍 bug?

objective-c - 为什么应用程序崩溃而没有在控制台中打印任何内容?

iphone - 如何在应用更新下载后再次调用 didFinishLaunchingWithOptions

ios - 如何在没有NavgationController的情况下打开UIViewControllers并保持状态

javascript - IOS WebRTC js 黑屏

ios - WebStorm - React-Native App 模拟器不工作

objective-c - 检查 NavigationItem.title 是否等于 @"part"

iphone - 如何在表格单元格按钮中执行操作

iphone - UIView:如何进行无损绘制?

ios - UIView(或 UIWebView)中的视频