我有一个自定义的 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];
}
和一个 Controller 类
。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
我现在想从我的 Controller 调用 NSView 的 setTheShallDraw 以便在一个矩形内显示一个 NSImage。
我的问题是,虽然 setTheShallDraw 方法被调用,但 drawRect 方法不绘制图像。我到底错过了什么?
这只是一个实验项目,我需要这个用于涉及合成图像的更复杂的项目,因此仅在 IB 中使用 NSImageView 不会成功。
最佳答案
在您的代码中,您没有将 CustomView 实例添加到 View 层次结构中...
- (IBAction)goButton:(id)sender {
CustomView *cv = [[CustomView alloc]init];
// add CustomView to view hierarchy
[theContentView addSubview:cv];
[cv setTheShallDraw:YES];
}
关于objective-c - drawRect 不绘制 NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656266/