简体   繁体   English

如何在WPF中自定义滑块控件(如音量)

[英]How to custom slider control like sound volumn in wpf

I am begin to study in Wpf, I want to use slider but I want to custom the slider control like image below: 我开始在Wpf中学习,我想使用滑块,但想自定义滑块控件,如下图所示:

在此处输入图片说明

The value of slider will be some of column with height increase like chart, and default column background color is black. 滑块的值将是某些像图表一样高度增加的列,并且默认的列背景颜色是黑色。 When User drag and move from left to right, the column background of left side will be green color and opposite, the color will be black again. 当用户从左向右拖动并移动时,左侧的列背景将变为绿色,而相反的方向,该颜色将再次变为黑色。 Please let me know if my question is not clear. 如果我的问题不清楚,请告诉我。

I found the solution by myself. 我自己找到了解决方案。 I have two image stack up together, green background image is at bottom and black background image is at top. 我将两个图像堆叠在一起,绿色背景图像位于底部,黑色背景图像位于顶部。 I have two event: MouseMove and MouseDown on image will get the position of mouse and set the opacity mask of top image. 我有两个事件:图像上的MouseMove和MouseDown将获取鼠标的位置并设置顶部图像的不透明蒙版。 Opacity mask will set a part of image to transparent background. 不透明蒙版会将图像的一部分设置为透明背景。 Of course, the bottom image will be display. 当然,将显示底部图像。 See code below . 参见下面的代码。

    private void imgMusicBlack_MouseDown(object sender, MouseButtonEventArgs e)
    {
        var img = sender as Image;
        SetOpacityMask(img, e.GetPosition(img).X);
    }

    private void imgMusicBlack_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var img = sender as Image;
            SetOpacityMask(img, e.GetPosition(img).X);
        }            
    }

    private void SetOpacityMask(Image img, double pointX, double offset = -1)
    {
        if (offset == -1)
            offset = Math.Round(pointX / img.ActualWidth, 2);


        LinearGradientBrush linear = new LinearGradientBrush();
        linear.StartPoint = new Point(0, 0.5);
        linear.EndPoint = new Point(1, 0.5);
        linear.GradientStops = new GradientStopCollection();
        linear.GradientStops.Add(new GradientStop(Colors.Transparent, offset));
        linear.GradientStops.Add(new GradientStop(Colors.Black, offset));

        img.OpacityMask = linear;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM