3

NSImagecolorWithPatternImage方法从底部平铺图像。我可以从顶部平铺它们吗?

+ (NSColor *)colorWithPatternImage:(NSImage *)image Parameters image

用作颜色对象图案的图像。图像从窗口底部开始平铺。图像未缩放。

这是我在 IKImageBrowserView 子类中的代码,它是我应用程序中 NSScrollView 内的视图。

- (void)drawRect:(NSRect)rect
{
    NSImage * backgroundImage = [NSImage imageNamed:@"deliciousLibrary.png"];
    [backgroundImage setSize:NSMakeSize(459 * bgImageSize, 91 * bgImageSize)];
    [[NSColor colorWithPatternImage:backgroundImage] set];
    NSRectFill(rect);
    [super drawRect:rect];
}

谢谢

更新:我在互联网上找到了这个解决方案。但就我而言,它不起作用,因为图像不再在我的 NSScrollView 中滚动。

- (void)drawRect:(NSRect)dirtyRect {
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];
    [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,[self frame].size.height)];
    [self.customBackgroundColour set];
    NSRectFill([self bounds]);
    [theContext restoreGraphicsState]; 
}
4

2 回答 2

4

这是我的问题的解决方案。简单得惊人。

float yOffset = NSMaxY([self convertRect:[self frame] toView:nil]);
[[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,yOffset)];
于 2013-02-15T11:00:54.930 回答
0

这是 Swift 5 中公认的答案:

let yOffset = NSMaxY(self.convert(self.frame, to: nil))
NSGraphicsContext.current?.patternPhase = NSMakePoint(0, yOffset)

...和一个简单的示例实现:

class MyPatternedView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        // Make the pattern tile repeat from the top of the view.
        let yOffset = NSMaxY(self.convert(self.frame, to: nil))
        NSGraphicsContext.current?.patternPhase = NSMakePoint(0, yOffset)

        if let image = NSImage(named: "Bricks") {
            let color = NSColor.init(patternImage: image)
            color.setFill()
            dirtyRect.fill()
        }

        super.draw(dirtyRect)
    }

}

于 2020-05-28T01:53:55.917 回答