objective-c - drawRect 不绘制 NSImage

标签 objective-c nsview nsimage

我有一个自定义的 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/

相关文章:

iphone - NSNotifications 有哪些类型?

cocoa - BeginSheet不显示窗口

macos - 如何在 OS X 中获取图像文件的实际图像?

ios - 如何编辑 ABAddressBook 上的记录

iphone - 要在 iPhone 上显示的 URL 上的文本文件的内容

objective-c - 使用 Core Animation 呈现错误的文本

objective-c - 垂直数组 View ,可能是 NSOutlineView

cocoa - NSImage 变换后变得模糊

cocoa - NSRectFill 在视网膜 MBP 上绘制两倍大

objective-c - 使用 SUN RPC 将文件从客户端传输到服务器