2013-12-18 64 views
2

我有一個自定義的NSView的drawRect不拉絲NSImage中

的.h文件

#import <Cocoa/Cocoa.h> 

@interface CustomView : NSView 

@property BOOL shallDraw; 

- (void) setTheShallDraw:(BOOL)draw; 

@end 

的.m文件

#import "CustomView.h" 

@implementation CustomView 


- (id) initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code here. 
     _shallDraw = NO; 


    } 
    return self; 
} 

- (void)drawRect:(NSRect)dirtyRect 
{ 
    [super drawRect:dirtyRect]; 

    // Drawing code here. 


    if (_shallDraw) { 

     NSLog(@"Drawing image"); 
     NSString * file = @"/Users/mac2/Desktop/Test 1.jpg"; 
     NSImage * image = [[NSImage alloc] initWithContentsOfFile:file]; 

     if (image) { 
      NSLog(@"Image initialized"); 
     } 

     [image setFlipped:NO]; 

     NSSize customViewSize = NSMakeSize(self.bounds.size.width, self.bounds.size.height); 
     NSRect myRect = NSMakeRect(20, 20, customViewSize.height *5/7, customViewSize.height); 

     // Set Image Size to Rect Size 
     [image setSize:myRect.size]; 

     // Draw Image in Rect 
     [image drawInRect: myRect 
        fromRect: NSZeroRect 
        operation: NSCompositeSourceOver 
        fraction: 1.0]; 
    } 



} 

- (void) setTheShallDraw:(BOOL)draw{ 
    _shallDraw = draw; 
    NSLog(@"Method 1 called"); 
    [self setNeedsDisplay:YES]; 
} 

和控制器類

.H

#import <Foundation/Foundation.h> 
#import "CustomView.h" 

@interface Controller : NSObject 
- (IBAction)goButton:(id)sender; 
@end 

.M

#import "Controller.h" 

@implementation Controller 
- (IBAction)goButton:(id)sender { 

    CustomView *cv = [[CustomView alloc]init]; 
    [cv setTheShallDraw:YES]; 

} 

@end 

我現在想以一個矩形中顯示NSImage中調用的NSView的setTheShallDraw從我的控制器。

我的問題是,雖然方法setTheShallDraw被調用,drawRect方法不會繪製圖像。我錯過了什麼?

這只是一個實驗項目,我需要這個用於複雜圖像的更復雜的項目,所以在IB中只使用NSImageView並不能解決問題。

+0

待辦事項你得到日誌消息? 'image'是否已初始化?或者你是否將消息發送給'nil'? – blackbird

+0

我收到了「Method 1 called」消息,但沒有任何消息。 – user3114858

+0

我可能是錯誤的,因爲到目前爲止我只編寫了iOS,但不應該將自定義視圖添加到超級視圖? – blackbird

回答

0

drawRect:在呼叫[cv setTheShallDraw:YES];發生之前被呼叫。

因此,在initWithFrame:_shallDraw = NO;限制畫出你有:

if (_shallDraw) { 
    NSLog(@"Drawing image"); 
+0

但有一個'[self setNeedsDisplay:YES];',所以'drawRect:'應該再次調用,'_shallDraw == YES',對吧? – blackbird

+0

setTheShallDraw應該將_shallDraw更改爲YES。 不應該setNeedsDisplay調用drawRect多一次? – user3114858

+0

哦,我錯過了,PLZ標記一個斷點,並檢查它是否被調用兩次或沒有。 –

0

在你的代碼,你就不是你的CustomView實例添加到視圖層次...

- (IBAction)goButton:(id)sender { 

    CustomView *cv = [[CustomView alloc]init]; 

    // add CustomView to view hierarchy 
    [theContentView addSubview:cv]; 

    [cv setTheShallDraw:YES]; 
} 
+0

我應該如何聲明內容視圖? cv的父視圖是窗口? – user3114858

+0

如果你使用window的contentView作爲父窗口使用'[[window contentView] addSubview:cv];' – Emmanuel