簡體   English   中英

UIView 子類:未調用 drawRect

[英]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子類,其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的問題是沒有進行繪圖,並且在NSLog我有“正在初始化”消息,但沒有“繪圖”消息。

所以基本上它使initWithFrame ,但它不調用drawRect方法。

你能指出我做錯了什么嗎?

  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

保羅,

您可以嘗試以下幾點:

  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);

可能問題是自定義視圖的框架是 (0,0,0,0)。
你可以嘗試傳遞一個常量 CGRect 參數,像這樣: CGRectMake(5, 5, 100, 100)。

我的情況的答案與我為類似問題閱讀的所有答案不同,也許會幫助其他人。 事實證明,在我的故事板上,“從目標繼承模塊”未選中,而同時模塊為無。 我添加了復選標記,下次運行應用程序時會調用 draw 方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM