gpt4 book ai didi

objective-c - NSView 永久绘制到背景

转载 作者:行者123 更新时间:2023-12-03 16:36:28 24 4
gpt4 key购买 nike

我正在尝试在窗口背景上画一些东西。因此,我对窗口的 NSView 进行了子类化,并添加了一些绘图代码,如下所示:

- (void)drawRect:(NSRect)dirtyRect {
float color = 0.95;
[[NSColor colorWithDeviceRed:color green:color blue:color alpha:1.0] set];
NSRectFill(NSMakeRect(320, 0, 220, NSHeight(dirtyRect)-60));
}

这很好用,但是一旦我打开 NSComboBox 或激活复选框,这些元素的背景就会删除我刚刚绘制的矩形。

我不明白这一点,因为检查例如复选框会导致调用drawRect(我添加了一个NSLog)。只有调整窗口大小才能再次绘制我的矩形。

编辑:这是问题的屏幕截图:

enter image description here

最佳答案

我有时也会遇到同样的问题。我认为以下是我使用的。

/// .h
@interface BackgroundView1 : NSView {
NSImage *myImage;
}

// .m
- (void)awakeFromNib {
[self setupBackgroundImage];
}

- (void)setupBackgroundImage {
NSColor *c = [NSColor colorWithDeviceRed:0.0f/255.0f green:55.0f/255.0f blue:150.0f/255.0f alpha:1.0f];
if (myImage == nil)
myImage = [self createColorImage:NSMakeSize(1,1):c];
}

- (void)drawRect:(NSRect)rect {
[myImage drawInRect:NSMakeRect([self bounds].origin.x,[self bounds].origin.y,[self frame].size.width,[self frame].size.height)
fromRect:NSMakeRect(0,0,[myImage size].width, [myImage size].height)
operation:NSCompositeCopy
fraction:1.0];
}

// Start Functions //
- (NSImage *)createColorImage:(NSSize)size :(NSColor *)color {
NSImage *image = [[NSImage alloc] initWithSize:size];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:size.width
pixelsHigh:size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:0
bitsPerPixel:0];

[image addRepresentation:rep];
[image lockFocus]; // Lock focus of image, making it a destination for drawing
[color set];
NSRectFill(NSMakeRect(0,0,size.width,size.height));
[image unlockFocus];
return image;
}
// End Functions //

关于objective-c - NSView 永久绘制到背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com