V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
bitweaver
V2EX  ›  问与答

cocoa 自定义 View,如何擦除背景一小块,露出下面的内容?

  •  
  •   bitweaver · 2014-12-02 21:57:01 +08:00 · 2608 次点击
    这是一个创建于 3493 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我写的是osx桌面程序。
    我试过两个方法
    1、[[NSGraphicsContext currentContext] setCompositingOperation:NSCompositeDestinationOut];
    [NSBezierPath fillRect:win];
    2、或者NSRectFillUsingOperation(win, NSCompositeDestinationOut);
    还有Copy,Clear等Composite属性都试过了,擦完以后只剩一块黑色背景,而不是我期望的透明背景。
    后面我还尝试在画矩形前设置一下颜色
    [[NSColor clearColor] set];
    同样是黑色。
    第 1 条附言  ·  2014-12-03 00:09:44 +08:00
    在stackoverflow上也去问了一下, http://stackoverflow.com/questions/27253107/cocoa-erase-a-part-of-a-custom-nsview-and-show-the-content-beneath
    希望不要沉贴,大神快来相助吧!!!
    6 条回复    2014-12-03 17:10:31 +08:00
    ashong
        1
    ashong  
       2014-12-03 00:55:50 +08:00 via iPad
    setClip
    WildCat
        2
    WildCat  
       2014-12-03 07:08:13 +08:00 via iPhone
    @ashong 正解!
    bitweaver
        3
    bitweaver  
    OP
       2014-12-03 08:15:41 +08:00
    @ashong 你的意思是让我在填充背景的时候设置裁剪区域,把需要擦除的地方空出来吗?还是其他什么方法,能详细说明一下吗?
    ashong
        4
    ashong  
       2014-12-03 16:41:37 +08:00
    @bitweaver
    [[NSBezierPath bezierPathWithRect:NSMakeRect(x,y,w,h)] setClip];

    or

    [NSBezierPath clipRect:NSMakeRect(x,y,w,h)];
    ashong
        5
    ashong  
       2014-12-03 16:54:09 +08:00   ❤️ 1
    上面是设置rect为剪裁区域, 你的需求时掏洞, 应该是这样的

    NSBezierPath* path = [NSBezierPath bezierPathWithRect: outerRect];
    [path appendBezierPathWithRect: innerRect];

    [path setWindingRule: NSEvenOddWindingRule];
    [path setClip];
    bitweaver
        6
    bitweaver  
    OP
       2014-12-03 17:10:31 +08:00
    @ashong 你的代码解释地很清楚,多谢耐心指教。但是这种填充的方案并不是我的首选方案。如果你看了一下stackoverflow上的问题描述,其实我不光想擦除大方框内的背景,四个控制点的背景我也想擦掉。如果写path,还是比较麻烦的。同时我也做了一个实验,在位图上作画,结果和在屏幕上是不一样的,NSCompositeClear是可以擦掉source轮廓内所有内容的。好像问题有了一些转机。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3286 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 107ms · UTC 10:48 · PVG 18:48 · LAX 03:48 · JFK 06:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.