Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

WPF Color Picker on Color Cube, Black White Color

 

 

This code example contains a color picker (ColorPicker) with which you can determine a color at run-time in RGB values.

The color is returned, over which the mouse pointer is positioned as a cursor.

 

ColorWheel, SelectColor in C #, WPF

 

 

Video Tutorial

 

Short C # Code Description:

 

1.     A current bitmap is created by the displayed element

2.     Then a 1-pixel wide bitmap where the cursor stands

3.     Then the pixel is copied into an array

4.     And final the array pixel as red-green-blue values are transferred into a result field.

                //< get Bitmap of Image-Element >

                BitmapSource visual_BitmapSource = get_BitmapSource_of_Element( imgCubeWhite  );

                //</ get Bitmap of Image-Element >

 

                //< get 1-Pixel Bitmap at Cursor >

                CroppedBitmap cb = new CroppedBitmap(visual_BitmapSource, new Int32Rect((int)Mouse.GetPosition(imgCubeWhite).X, (int)Mouse.GetPosition(imgCubeWhite).Y, 1, 1));

                //</ get 1-Pixel Bitmap at Cursor >

 

                //< transfer in byte-Array >

                byte[] pixels = new byte[4];               

                try

                {

                    cb.CopyPixels(pixels, 4, 0);

                }

                catch (Exception)

                {

                    //error

                }

                //</ transfer in byte-Array >

 

 

                //< fill Selected-Rectangle >

                rectSelected.Fill = new SolidColorBrush(Color.FromRgb(pixels[2], pixels[1], pixels[0]));

                //</ fill Selected-Rectangle >

 

 

 

 

The C # code is located in the UcColorSelector.xaml file

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace wpf_Color_Selector._UserControls

{

    /// <summary>

    /// Interaction logic for UcColorSelector.xaml

    /// </summary>

    public partial class UcColorSelector : UserControl

    {

        public UcColorSelector()

        {

            InitializeComponent();

        }

 

        private void btnSelect_Click(object sender, RoutedEventArgs e)

        {

            //select_Color();

        }

 

        private void slider_Color_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)

        {

            //------------< slider_Color_ValueChanged() >------------

            //*change Cube from White to Black

            if (rectColor_Background != null)

            {

                double imgOpacity = slider_Color.Value;

                imgCubeWhite.Opacity = imgOpacity;

            }

            //------------</ slider_Color_ValueChanged() >------------

        }

 

        private void imgCubeWhite_MouseMove(object sender, MouseEventArgs e)

        {

            //------------< imgCubeWhite_MouseMove() >------------

            select_Color(sender, e);

            //------------</ imgCubeWhite_MouseMove() >------------

        }

 

 

        private void select_Color(object sender, MouseEventArgs e)

        {

            try

            {

 

                BitmapSource visual_BitmapSource = get_BitmapSource_of_Element( imgCubeWhite  );

                CroppedBitmap cb = new CroppedBitmap(visual_BitmapSource, new Int32Rect((int)Mouse.GetPosition(imgCubeWhite).X, (int)Mouse.GetPosition(imgCubeWhite).Y, 1, 1));

 

                byte[] pixels = new byte[4];

 

                try

                {

                    cb.CopyPixels(pixels, 4, 0);

                }

                catch (Exception)

                {

                    //error

                }

                rectSelected.Fill = new SolidColorBrush(Color.FromRgb(pixels[2], pixels[1], pixels[0]));

            }

            catch (Exception)

            {

                //not much we can do

            }

        }

 

 

 

        public  BitmapSource get_BitmapSource_of_Element(FrameworkElement  element)

        {

            //-------------< get_BitmapSource_of_Element() >------------

            //< check >

            if (element == null){return null;}

            //</ check >

 

            //< init >

            double dpi = 96;

            Double width = element.ActualWidth;

            Double height = element.ActualHeight;

            //</ init >

 

            RenderTargetBitmap bitmap_of_Element = null;

            if(bitmap_of_Element==null)

            {

                try

                {

                    //< create empty Bitmap of element >

                    bitmap_of_Element = new RenderTargetBitmap((int) width , (int)height, dpi, dpi, PixelFormats.Default );

                    //</ create empty Bitmap of element >

 

                    //----< render area into bitmap >----

                    DrawingVisual visual_area = new DrawingVisual();

                    using (DrawingContext dc = visual_area.RenderOpen())

                    {

                        VisualBrush visual_brush = new VisualBrush(element );

                        dc.DrawRectangle(visual_brush, null, new Rect(new Point(), new Size(width, height)));

                    }

 

                    //< render >

                    bitmap_of_Element.Render(visual_area);

                    //</ render >

                    //----</ render area into bitmap >----

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);               

                }

            }

            return bitmap_of_Element;

            //-------------</ get_BitmapSource_of_Element() >------------

        }

    }

}

 

 

 

 

 

 

XAML of UCColorSelector UserControl

<UserControl x:Class="wpf_Color_Selector._UserControls.UcColorSelector"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

             xmlns:local="clr-namespace:wpf_Color_Selector._UserControls"

             mc:Ignorable="d"

             d:DesignHeight="300" d:DesignWidth="300">

    <Grid x:Name="Grid_Usercontrol">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="131*"/>

            <ColumnDefinition Width="19*"/>

        </Grid.ColumnDefinitions>

        <Grid Grid.Column="1" >

            <Grid.RowDefinitions>

                <RowDefinition Height="20"/>

                <RowDefinition Height="20"/>

                <RowDefinition Height ="*"/>

            </Grid.RowDefinitions>

            <Button x:Name="btnSelect" Content="Select" Grid.Row="0" Click="btnSelect_Click"/>

            <Rectangle x:Name="rectSelected" Grid.Row="1"></Rectangle>

            <Rectangle Grid.Row="2" VerticalAlignment="Stretch" >

                <Rectangle.Fill>

                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                       

                        <GradientStop Color="White" Offset="0"/>

                        <GradientStop Color="Black" Offset="1"/>

                    </LinearGradientBrush>

                </Rectangle.Fill>

            </Rectangle>

            <Slider x:Name="slider_Color"  Grid.Row="2" Orientation="Vertical" Minimum="0" Maximum="1" Value="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" ValueChanged="slider_Color_ValueChanged"></Slider>

 

        </Grid>

 

        <Grid Grid.Column="0" x:Name="GridColors" >

            <Rectangle x:Name="rectColor_Background" >

                <Rectangle.Fill>

                <RadialGradientBrush >

                    <GradientStop Color="White" Offset="1"/>

                    <GradientStop Color="White" x:Name="gradStopCenter"/>

                </RadialGradientBrush>

                    </Rectangle.Fill>

            </Rectangle>

           

            <Image x:Name="imgCubeBlack"

                   Source="/wpf_Color_Selector;component/_images/RGB_Colorcube_Corner_Black.png" ></Image>

            <Image x:Name="imgCubeWhite" MouseMove="imgCubeWhite_MouseMove"

                   Source="/wpf_Color_Selector;component/_images/RGB_Colorcube_Corner_White.png"  ></Image>

        </Grid>

    </Grid>

</UserControl>

 

 

 

Mobile
»
WPF / UWP: Canvas with relative positions and sizes
»
C #, WPF, UWP: ScreenShot to save an app or window area as a file
»
C #: Windows ScreenShot save as file
»
WPF Color Picker on Color Cube
»
WPF: Draw ColorWheel in C# by drawing Lines
»
WPF: Snap In to Next Lines of Elements
»
WPF Code: Usercontrol with customizable size at runtime
»
WPF: Save the background of a Windows app as a ScreenShot
»
WPF, UWP: Create transparent app window
»
WPF: Determine the relative position of an element

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de