绘制透明图像
我为按钮创建了一个自定义视图,因为我需要在鼠标悬停时实现一些突出显示。该类非常简单,我已经实现了 mouseEntered:
以及 mouseExited:
。该视图已在 init 方法中注册用于跟踪(不确定它是否是最佳位置)。
问题是画图。我保留一个 ivar mouseOver
,在鼠标进入时设置为 YES
,在鼠标退出时设置为 NO
。另一个 ivar 用于图像,称为 image
。绘图时鼠标悬停与否的区别在于透明度。这是我的 drawRect:
:
- (void)drawRect:(NSRect)dirtyRect
{
[image drawAtPoint:NSMakePoint(0.0,0.0)
fromRect:dirtyRect
operation:NSCompositeCopy
fraction:((mouseOver) ? 1.0 : 0.0)];
}
它工作得很好,但显然只有当鼠标第一次进入时。我想问题是在绘制其他图像之前没有清除视图。我尝试添加:
[[NSColor clearColor] set];
NSRectFillUsingOperation(dirtyRect, NSCompositeClear);
但没有成功。我该如何解决这个问题?
I created a custom view to a button, as I need to implement some highlighting when the mouse is over. The class is very simple, and I already implemented mouseEntered:
as well as mouseExited:
. The view was registered for tracking in the init method (not sure if it's the best place).
The problem is drawing. I keep an ivar mouseOver
, set to YES
on mouse enter and NO
on mouse exited. The other ivar is for the image, called image
. The difference between mouse over or not when it comes to drawing, is the transparency. Here is my drawRect:
:
- (void)drawRect:(NSRect)dirtyRect
{
[image drawAtPoint:NSMakePoint(0.0,0.0)
fromRect:dirtyRect
operation:NSCompositeCopy
fraction:((mouseOver) ? 1.0 : 0.0)];
}
It works nicely, but only when the mouse first entered, apparently. I guess the problem is that the view is not cleared before drawing the other image. I tried adding:
[[NSColor clearColor] set];
NSRectFillUsingOperation(dirtyRect, NSCompositeClear);
But without success. How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[NSColor clearColor]
是纯透明颜色。您可能想使用具有一定不透明度的颜色进行填充,例如[NSColor WhiteColor]
。[NSColor clearColor]
is a purely transparent color. You probably want to fill using a color with some opacity, like, say,[NSColor whiteColor]
.