我有自定义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,以便在矩形中显示NSImage。
我的问题是,虽然调用方法setTheShallDraw,但drawRect方法不会绘制图像。我到底错过了什么?
这只是一个实验项目,我需要这个涉及合成图像的更复杂的项目,所以在IB中使用NSImageView是行不通的。
答案 0 :(得分:0)
drawRect:
在调用[cv setTheShallDraw:YES];
之前被调用。
因此,在initWithFrame:
中,_shallDraw = NO;
限制绘制:
if (_shallDraw) {
NSLog(@"Drawing image");
答案 1 :(得分:0)
在您的代码中,您不会将CustomView实例添加到视图层次结构......
- (IBAction)goButton:(id)sender {
CustomView *cv = [[CustomView alloc]init];
// add CustomView to view hierarchy
[theContentView addSubview:cv];
[cv setTheShallDraw:YES];
}