2012-03-31 80 views
9

我是iOS編程的初學者,很抱歉如果我的問題是一個愚蠢的問題。UIView子類:drawRect不叫

我想做一個應用程序執行加載的圖像自定義繪圖。

要做到這一點,我發現一個解決方案是子類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]; 

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

,我有是沒有描圖和NSLog我有問題「初始化」消息,但不是「繪圖」圖紙。

所以基本上它使得initWithFrame,但它不叫drawRect方法。

請問我能指出我做錯了什麼?

回答

5

保羅,

這裏有一些事情你可以嘗試:

    initWithFrame
  1. ,檢查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

謝謝,通過放置NSLog,我發現調用drawRect方法時出現錯誤。通過添加[previewView setNeedDisplay]方法被調用,但不是當我期望它完成時。我的意思是,通過以下代碼步驟,[previewView setNeedDisplay]行的執行不會使自定義繪圖出現,而是以某種方式出現。我想了解在哪一刻drawRect方法被調用,但無論如何,最初的問題得到解決,謝謝:) – Dobrodeveloper 2012-04-14 15:37:39

13
  1. 確保你的新視圖類的子類UIView的,而不是UIImageView的。
  2. 爲了確保新視圖顯示出來,您需要執行[viewContainer addSubView:]以獲取要調用的drawRect。從DOC

價:

UIImageView類被優化以繪製其圖像的顯示。 UIImageView不會調用drawRect:一個子類。如果您的子類需要自定義繪圖代碼,建議您使用UIView作爲基類。

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

+0

你可以設置自定義類,它重寫繪圖矩形編碼器 – Subhash 2016-03-03 14:51:36

2

可能問題是aCustomView的幀是(0,0,0,0)。
您可以嘗試傳遞一個常量CGRect參數,如下所示:CGRectMake(5, 5, 100, 100)。