我有一個自定義的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並不能解決問題。
待辦事項你得到日誌消息? 'image'是否已初始化?或者你是否將消息發送給'nil'? – blackbird
我收到了「Method 1 called」消息,但沒有任何消息。 – user3114858
我可能是錯誤的,因爲到目前爲止我只編寫了iOS,但不應該將自定義視圖添加到超級視圖? – blackbird