在WPF不规则PNG按钮的单击事件 [英] Irregular PNG button's click event in WPF

查看:714
本文介绍了在WPF不规则PNG按钮的单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在WPF的不规则形状的按钮。我使用XAML做了这种方式:

I need an irregularly shaped button in WPF. I am doing it in this way using XAML:

<Button Name="toggleButton" Click="toggleButton_Click" Canvas.Left="177" Canvas.Top="0">
  <Button.Template>
    <ControlTemplate>
      <Image Source="ball.png" />
    </ControlTemplate>
  </Button.Template>
</Button>

我的ball.png图像是与它周围的透明区域,一个球一个PNG图像。该按钮可显示正常,但Click事件处理程序,即使当我短声上的​​图像的透明部分执行。

My ball.png image is a PNG image with a ball with transparent area around it. The button displays correctly, but Click event handler is executed even when I clik on the transparent part of the image.

有没有办法使用透明的PNG创建不规则的按钮?

Is there any way to create irregular buttons using transparent PNGs?

谢谢,米哈尔

推荐答案

您可以创建一个类继承自图像和覆盖<一href="http://msdn.microsoft.com/en-us/library/system.windows.media.visual.hittestcore.aspx">HitTestCore因此,它不响应命中测试在图像的透明部分,然后用一个简单的形象该类在你的模板。

You can create a class that inherits from Image and overrides HitTestCore so that it does not respond to hit testing over the transparent parts of an image, and then use that class in your template instead of a plain Image.

下面是一个例子,虽然code键检查透明像素不是很鲁棒,因为它使关于图像源和像素格式一些假设。如果你已经有code,以检查透明像素,那么你应该插在代替。

Here is an example, although the code to check for transparent pixels isn't very robust since it makes some assumptions about the image source and pixel format. If you already have code to check for transparent pixels then you should plug that in instead.

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);
    }
}

这篇关于在WPF不规则PNG按钮的单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆