2

有没有办法使用 jpeg/png 图像作为 NSTextField 的背景?

4

1 回答 1

10

1 解决方案:您可以简单地这样做:

NSImage *image = ...; //image for background
[_textfieldOutlet setBackgroundColor:[NSColor colorWithPatternImage:image]];

结果:

带有背景的 NSTextField


2 解决方案:您可以NSTextField像这样子类 Your :

#import "TextFieldSubclass.h"

@implementation TextFieldSubclass

- (void)awakeFromNib
{
    [self setDrawsBackground:NO];
}

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];

    NSImage *image = ...; //image for background
    [image setFlipped:YES]; //image need to be flipped

    //use this if You need borders

    NSRect rectForBorders = NSMakeRect(2, 2, rect.size.width-4, rect.size.height-4);
    [image drawInRect:rectForBorders fromRect:rectForBorders operation:NSCompositeSourceOver fraction:1.0];

    //if You don't need borders use this:

    //[image drawInRect:rect fromRect:rect operation:NSCompositeSourceOver fraction:1.0];
}

@end

带边框的结果:

带边框

结果无边框:

无国界

于 2012-05-16T07:33:10.997 回答