我是 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
子类,其init
和drawRect
方法设置如下:
- (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
方法。
你能指出我做错了什么吗?
最佳答案
- 确保您的新 View 类是 UIView 的子类,而不是 UIImageView。
- 为确保显示新 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.
关于ios - UIView 子类 : drawRect not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956565/