![](/img/trans.png)
[英]drawRect gets called on UIView subclass but not on UIViewController
[英]UIView subclass: drawRect not called
我是 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
子類,其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
的問題是沒有進行繪圖,並且在NSLog
我有“正在初始化”消息,但沒有“繪圖”消息。
所以基本上它使initWithFrame
,但它不調用drawRect
方法。
你能指出我做錯了什么嗎?
參考文檔:
UIImageView 類經過優化,可以將其圖像繪制到顯示器上。 UIImageView 不會調用 drawRect:一個子類。 如果您的子類需要自定義繪圖代碼,建議您使用 UIView 作為基類。
保羅,
您可以嘗試以下幾點:
initWithFrame
,檢查frame
變量是否包含您期望的內容: NSLog(@"Frame: %@", NSStringFromCGRect(frame));
[preview setNeedsDisplay];
將其添加到其超級視圖后最后,我會改變
image.frame = previewView.frame;
和:
image.bounds = CGRectMake(0, 0, previewView.frame.size.width, previewView.frame.size.height);
可能問題是自定義視圖的框架是 (0,0,0,0)。
你可以嘗試傳遞一個常量 CGRect 參數,像這樣: CGRectMake(5, 5, 100, 100)。
我的情況的答案與我為類似問題閱讀的所有答案不同,也許會幫助其他人。 事實證明,在我的故事板上,“從目標繼承模塊”未選中,而同時模塊為無。 我添加了復選標記,下次運行應用程序時會調用 draw 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.