使用图像作为NSTextField的背景

rsh*_*rma 2 cocoa objective-c

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

Jus*_*Boo 10

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

NSImage *image = ...; //image for background
[_textfieldOutlet setBackgroundColor:[NSColor colorWithPatternImage:image]];
Run Code Online (Sandbox Code Playgroud)

结果:

NSTextField与背景


2解决方案:你可以NSTextField像这样继承你的子类:

#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
Run Code Online (Sandbox Code Playgroud)

带边框的结果:

有边框

没有边框的结果:

没有边界