首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >未绘制NSImage的drawRect

未绘制NSImage的drawRect
EN

Stack Overflow用户
提问于 2013-12-18 18:58:58
回答 2查看 753关注 0票数 4

我有一个自定义的NSView

.h-文件

代码语言:javascript
运行
复制
#import <Cocoa/Cocoa.h>

@interface CustomView : NSView

@property BOOL shallDraw;

- (void) setTheShallDraw:(BOOL)draw;

@end

.m-文件

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
#import <Foundation/Foundation.h>
#import "CustomView.h"

@interface Controller : NSObject
- (IBAction)goButton:(id)sender;
@end

.m

代码语言:javascript
运行
复制
#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不会起到作用。

EN

回答 2

Stack Overflow用户

发布于 2013-12-18 21:10:31

在您的代码中,您没有将CustomView实例添加到视图层次结构中...

代码语言:javascript
运行
复制
- (IBAction)goButton:(id)sender {

    CustomView *cv = [[CustomView alloc]init];

    // add CustomView to view hierarchy
    [theContentView addSubview:cv];

    [cv setTheShallDraw:YES];
}
票数 1
EN

Stack Overflow用户

发布于 2013-12-18 19:03:25

在调用[cv setTheShallDraw:YES];之前调用drawRect:

因此,在initWithFrame:中,_shallDraw = NO;限制为绘制,如您所拥有的:

代码语言:javascript
运行
复制
 if (_shallDraw) {
    NSLog(@"Drawing image");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20656266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档