Mic*_*zyk 7 .net c# wpf wpf-controls
在WPF中我需要一个不规则形状的按钮.我是这样用XAML做的:
<Button Name="toggleButton" Click="toggleButton_Click" Canvas.Left="177" Canvas.Top="0">
<Button.Template>
<ControlTemplate>
<Image Source="ball.png" />
</ControlTemplate>
</Button.Template>
</Button>
Run Code Online (Sandbox Code Playgroud)
我的ball.png图像是一张PNG图像,周围有一个透明区域的球.该按钮显示正确,但即使我克隆图像的透明部分,也会执行Click事件处理程序.
有没有办法使用透明PNG创建不规则按钮?
谢谢,米哈尔
Qua*_*ter 13
您可以创建一个继承自Image并重写HitTestCore的类,这样它就不会响应图像透明部分的命中测试,然后在模板中使用该类而不是普通的Image.
这是一个例子,虽然检查透明像素的代码不是很强大,因为它对图像源和像素格式做了一些假设.如果您已经有代码来检查透明像素,那么您应该将其插入.
public class TransparentImage
: Image
{
protected override HitTestResult HitTestCore(
PointHitTestParameters hitTestParameters)
{
// Get value of current pixel
var source = (BitmapSource)Source;
var x = (int)(hitTestParameters.HitPoint.X /
ActualWidth * source.PixelWidth);
var y = (int)(hitTestParameters.HitPoint.Y /
ActualHeight * source.PixelHeight);
var pixels = new byte[4];
source.CopyPixels(new Int32Rect(x, y, 1, 1), pixels, 4, 0);
// Check alpha channel
if (pixels[3] < 10)
{
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
else
{
return null;
}
}
protected override GeometryHitTestResult HitTestCore(
GeometryHitTestParameters hitTestParameters)
{
// Do something similar here, possibly checking every pixel within
// the hitTestParameters.HitGeometry.Bounds rectangle
return base.HitTestCore(hitTestParameters);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3367 次 |
最近记录: |