我有一个自定义的NSView
.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现在我想从我的控制器调用NSView的setTheShallDraw,以便在rect中显示一个NSImage。
我的问题是,尽管调用了setTheShallDraw方法,但drawRect方法并不绘制图像。我到底错过了什么?
这只是一个实验项目,我需要为一个更复杂的项目涉及复合图像,所以仅仅使用IB中的NSImageView不会起到作用。
发布于 2013-12-18 21:10:31
在您的代码中,您没有将CustomView实例添加到视图层次结构中...
- (IBAction)goButton:(id)sender {
CustomView *cv = [[CustomView alloc]init];
// add CustomView to view hierarchy
[theContentView addSubview:cv];
[cv setTheShallDraw:YES];
}https://stackoverflow.com/questions/20656266
复制相似问题