첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestSolution.zip
0.19MB

[TestLibrary 프로젝트]

 

▶ ColorToSolidColorBrushConverter.cs

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace TestLibrary
{
    /// <summary>
    /// 색상→단색 브러시 변환자
    /// </summary>
    [ValueConversion(typeof(Color), typeof(Brush))]
    public class ColorToSolidColorBrushConverter : IValueConverter
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 변환하기 - Convert(sourceValue, targetType, parameter, cultureInfo)

        /// <summary>
        /// 변환하기
        /// </summary>
        /// <param name="sourceValue">소스 값</param>
        /// <param name="targetType">타겟 타입</param>
        /// <param name="parameter">매개 변수</param>
        /// <param name="cultureInfo">문화 정보</param>
        /// <returns>변환 값</returns>
        public object Convert(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo)
        {
            if(targetType != typeof(Brush))
            {
                return sourceValue;
            }

            if(sourceValue == null || sourceValue == DependencyProperty.UnsetValue || sourceValue.GetType() != typeof(Color))
            {
                return Brushes.Transparent;
            }

            Color color = (Color)sourceValue;

            return new SolidColorBrush(color);
        }

        #endregion
        #region 역변환하기 - ConvertBack(sourceValue, targetType, parameter, cultureInfo)

        /// <summary>
        /// 역변환하기
        /// </summary>
        /// <param name="sourceValue">소스 값</param>
        /// <param name="targetType">타겟 타입</param>
        /// <param name="parameter">매개 변수</param>
        /// <param name="cultureInfo">문화 정보</param>
        /// <returns>역변환 값</returns>
        public object ConvertBack(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

 

728x90

 

▶ ImageColorPicker.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace TestLibrary
{
    /// <summary>
    /// 이미지 색상 선택기
    /// </summary>
    public class ImageColorPicker : Image
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 셀렉터 속성 - SelectorProperty

        /// <summary>
        /// 셀렉터 속성
        /// </summary>
        public static readonly DependencyProperty SelectorProperty = DependencyProperty.Register
        (
            "Selector",
            typeof(Drawing),
            typeof(ImageColorPicker),
            new FrameworkPropertyMetadata
            (
                new GeometryDrawing(Brushes.White, new Pen(Brushes.Black, 1),
                new EllipseGeometry(new Point(), 5, 5)),
                FrameworkPropertyMetadataOptions.AffectsRender
            ),
            ValidateSelectorPropertyValueCallback
        );

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property Key
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 선택 색상 속성 키 - SelectedColorPropertyKey

        /// <summary>
        /// 선택 색상 속성 키
        /// </summary>
        private static readonly DependencyPropertyKey SelectedColorPropertyKey = DependencyProperty.RegisterReadOnly
        (
            "SelectedColor",
            typeof(Color), typeof(ImageColorPicker),
            new FrameworkPropertyMetadata
            (
                Colors.Transparent,
                FrameworkPropertyMetadataOptions.AffectsRender
            )
        );

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 타겟 비트맵
        /// </summary>
        private RenderTargetBitmap targetBitmap;

        /// <summary>
        /// 위치
        /// </summary>
        private Point position = new Point();

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 셀렉터 - Selector

        /// <summary>
        /// 셀렉터
        /// </summary>
        public Drawing Selector
        {
            get
            {
                return (Drawing)GetValue(SelectorProperty);
            }
            set
            {
                SetValue(SelectorProperty, value);
            }
        }

        #endregion
        #region 위치 - Position

        /// <summary>
        /// 위치
        /// </summary>
        Point Position
        {
            get
            {
                return this.position;
            }
            set
            {
                Point newPosition = GetPosition(value);

                if(this.position != newPosition)
                {
                    this.position = newPosition;

                    Color color = GetColor(this.position.X, this.position.Y);

                    if(color == SelectedColor)
                    {
                        InvalidateVisual();
                    }

                    SetValue(SelectedColorPropertyKey, color);
                }
            }
        }

        #endregion
        #region 선택 색상 - SelectedColor

        /// <summary>
        /// 선택 색상
        /// </summary>
        public Color SelectedColor
        {
            get
            {
                return (Color)GetValue(SelectedColorPropertyKey.DependencyProperty);
            }
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 타겟 비트맵

        /// <summary>
        /// 타겟 비트맵
        /// </summary>
        private RenderTargetBitmap TargetBitmap
        {
            get 
            {
                if(this.targetBitmap == null)
                {
                    DrawingImage drawingImage = Source as DrawingImage;

                    if(drawingImage != null)
                    {
                        DrawingVisual drawingVisual = new DrawingVisual();

                        using(DrawingContext drawingContext = drawingVisual.RenderOpen())
                        {
                            drawingContext.DrawDrawing(drawingImage.Drawing);
                        }

                        Rect rectangle = drawingVisual.ContentBounds;

                        drawingVisual.Transform = new ScaleTransform
                        (
                            ActualWidth  / rectangle.Width,
                            ActualHeight / rectangle.Height
                        );

                        this.targetBitmap = new RenderTargetBitmap
                        (
                            (int)ActualWidth,
                            (int)ActualHeight,
                            96,
                            96,
                            PixelFormats.Pbgra32
                        );

                        this.targetBitmap.Render(drawingVisual);
                    }
                }

                return this.targetBitmap; 
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 셀렉터 속성 값 검증시 콜백 처리하기 - ValidateSelectorPropertyValueCallback(value)

        /// <summary>
        /// 셀렉터 속성 값 검증시 콜백 처리하기
        /// </summary>
        /// <param name="value">값</param>
        /// <returns>셀렉터 속성 값 검증 결과</returns>
        private static bool ValidateSelectorPropertyValueCallback(object value)
        {
            return value == null ? false : true;
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Instance
        //////////////////////////////////////////////////////////////////////////////// Protected

        #region 속성 변경시 처리하기 - OnPropertyChanged(e)

        /// <summary>
        /// 속성 변경시 처리하기
        /// </summary>
        /// <param name="e">이벤트 인자</param>
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if(e.Property.Name == "Source")
            {
                this.targetBitmap = null;

                Position = new Point();
            }

            base.OnPropertyChanged(e);
        }

        #endregion
        #region 렌더링 크기 변경시 처리하기 - OnRenderSizeChanged(info)

        /// <summary>
        /// 렌더링 크기 변경시 처리하기
        /// </summary>
        /// <param name="info">크기 변경시 정보</param>
        protected override void OnRenderSizeChanged(SizeChangedInfo info)
        {
            base.OnRenderSizeChanged(info);

            this.targetBitmap = null;

            if(info.PreviousSize.Width > 0 && info.PreviousSize.Height > 0)
            {
                Position = new Point
                (
                    Position.X * info.NewSize.Width  / info.PreviousSize.Width,
                    Position.Y * info.NewSize.Height / info.PreviousSize.Height
                );
            }
        }

        #endregion
        #region 렌더링시 처리하기 - OnRender(context)

        /// <summary>
        /// 렌더링시 처리하기
        /// </summary>
        /// <param name="context">드로잉 컨텍스트</param>
        protected override void OnRender(DrawingContext context)
        {
            base.OnRender(context);

            if(ActualWidth == 0 || ActualHeight == 0)
            {
                return;
            }

            context.PushTransform(new TranslateTransform(Position.X, Position.Y));

            context.DrawDrawing(Selector);

            context.Pop();
        }

        #endregion

        #region 마우스 진입시 처리하기 - OnMouseEnter(e)

        /// <summary>
        /// 마우스 진입시 처리하기
        /// </summary>
        /// <param name="e">이벤트 인자</param>
        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);

            if(e.LeftButton == MouseButtonState.Pressed)
            {
                Point mousePoint = e.GetPosition(this);

                Position = new Point(mousePoint.X, mousePoint.Y);
            }
        }

        #endregion
        #region 마우스 왼쪽 버튼 DOWN 처리하기 - OnMouseLeftButtonDown(e)

        /// <summary>
        /// 마우스 왼쪽 버튼 DOWN 처리하기
        /// </summary>
        /// <param name="e">이벤트 인자</param>
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);

            SetPosition(e.GetPosition(this));
        }

        #endregion
        #region 마우스 이동시 처리하기 - OnMouseMove(e)

        /// <summary>
        /// 마우스 이동시 처리하기
        /// </summary>
        /// <param name="e">이벤트 인자</param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            if(e.LeftButton == MouseButtonState.Pressed)
            {
                SetPosition(e.GetPosition(this));
            }
        }

        #endregion
        #region 마우스 왼쪽 버튼 UP 처리하기 - OnMouseLeftButtonUp(e)

        /// <summary>
        /// 마우스 왼쪽 버튼 UP 처리하기
        /// </summary>
        /// <param name="e">이벤트 인자</param>
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonUp(e);

            SetPosition(e.GetPosition(this));
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Private

        #region 위치 구하기 - GetPosition(sourcePoint)

        /// <summary>
        /// 위치 구하기
        /// </summary>
        /// <param name="sourcePoint">소스 위치</param>
        /// <returns>위치</returns>
        private Point GetPosition(Point sourcePoint)
        {
            double x = sourcePoint.X;
            double y = sourcePoint.Y;

            if(x < 0)
            {
                x = 0;
            }
            else if(x > ActualWidth)
            {
                x = ActualWidth;
            }
            
            if(y < 0)
            {
                y = 0;
            }
            else if(y > ActualHeight)
            {
                y = ActualHeight;
            }
            
            return new Point(x, y);
        }

        #endregion
        #region 위치 설정하기 - SetPosition(sourcePoint)

        /// <summary>
        /// 위치 설정하기
        /// </summary>
        /// <param name="sourcePoint">소스 포인트</param>
        private void SetPosition(Point sourcePoint)
        {
            if(sourcePoint.X >= 0 && sourcePoint.X <= ActualWidth && sourcePoint.Y >= 0 && sourcePoint.Y <= ActualHeight)
            {
                Position = sourcePoint;
            }
        }

        #endregion
        #region 색상 구하기 - GetColor(x, y)

        /// <summary>
        /// 색상 구하기
        /// </summary>
        /// <param name="x">X</param>
        /// <param name="y">Y</param>
        /// <returns>색상</returns>
        private Color GetColor(double x, double y)
        {
            if(Source == null)
            {
                throw new InvalidOperationException("Image Source not set");
            }
            
            BitmapSource bitmapSource = Source as BitmapSource;

            if(bitmapSource != null)
            {
                x *= bitmapSource.PixelWidth / ActualWidth;

                if((int)x > bitmapSource.PixelWidth - 1)
                {
                    x = bitmapSource.PixelWidth - 1;
                }
                else if(x < 0)
                {
                    x = 0;
                }

                y *= bitmapSource.PixelHeight / ActualHeight;

                if((int)y > bitmapSource.PixelHeight - 1)
                {
                    y = bitmapSource.PixelHeight - 1;
                }
                else if(y < 0)
                {
                    y = 0;
                }

                if(bitmapSource.Format == PixelFormats.Indexed4)
                {
                    byte[] pixelByteArray = new byte[1];

                    int stride = (bitmapSource.PixelWidth * bitmapSource.Format.BitsPerPixel + 3) / 4;

                    bitmapSource.CopyPixels(new Int32Rect((int)x, (int)y, 1, 1), pixelByteArray, stride, 0);

                    return bitmapSource.Palette.Colors[pixelByteArray[0] >> 4];
                }
                else if(bitmapSource.Format == PixelFormats.Indexed8)
                {
                    byte[] pixelByteArray = new byte[1];

                    int stride = (bitmapSource.PixelWidth * bitmapSource.Format.BitsPerPixel + 7) / 8;

                    bitmapSource.CopyPixels(new Int32Rect((int)x, (int)y, 1, 1), pixelByteArray, stride, 0);

                    return bitmapSource.Palette.Colors[pixelByteArray[0]];
                }
                else
                {
                    byte[] pixelByteArray = new byte[4];

                    int stride = (bitmapSource.PixelWidth * bitmapSource.Format.BitsPerPixel + 7) / 8;

                    bitmapSource.CopyPixels(new Int32Rect((int)x, (int)y, 1, 1), pixelByteArray, stride, 0);

                    return Color.FromArgb(pixelByteArray[3], pixelByteArray[2], pixelByteArray[1], pixelByteArray[0]);
                }
            }

            DrawingImage drawingImage = Source as DrawingImage;

            if(drawingImage != null)
            {
                RenderTargetBitmap renderTargetBitmap = TargetBitmap;

                x *= renderTargetBitmap.PixelWidth / ActualWidth;

                if((int)x > renderTargetBitmap.PixelWidth - 1)
                {
                    x = renderTargetBitmap.PixelWidth - 1;
                }
                else if(x < 0)
                {
                    x = 0;
                }

                y *= renderTargetBitmap.PixelHeight / ActualHeight;

                if((int)y > renderTargetBitmap.PixelHeight - 1)
                {
                    y = renderTargetBitmap.PixelHeight - 1;
                }
                else if(y < 0)
                {
                    y = 0;
                }

                byte[] pixelByteArray = new byte[4];

                int stride = (renderTargetBitmap.PixelWidth * renderTargetBitmap.Format.BitsPerPixel + 7) / 8;

                renderTargetBitmap.CopyPixels(new Int32Rect((int)x, (int)y, 1, 1), pixelByteArray, stride, 0);

                return Color.FromArgb(pixelByteArray[3], pixelByteArray[2], pixelByteArray[1], pixelByteArray[0]);
            }

            throw new InvalidOperationException("Unsupported Image Source Type");
        }

        #endregion
    }
}

 

반응형

 

[TestProject1 프로젝트]

 

▶ MainWindow.xaml

<Window x:Class="TestProject1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:library="clr-namespace:TestLibrary;assembly=TestLibrary"
    Width="800"
    Height="600"
    Title="Image 클래스 : 이미지 색상 선택기 사용하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Window.Resources>
        <library:ColorToSolidColorBrushConverter x:Key="ColorToSolidColorBrushConverterKey" />
        <RadialGradientBrush x:Key="RadialGradientBrushKey">
            <GradientStop Offset="0" Color="white"   />
            <GradientStop Offset="1" Color="#ff6161" />
        </RadialGradientBrush>
        <DrawingImage x:Key="DrawingImageKey">
            <DrawingImage.Drawing>
                <DrawingGroup>
                    <DrawingGroup.Children>
                        <GeometryDrawing
                            Geometry="M 1467.5 1852.5 c 0 110 -90 200 -200 200 h -1067 c -110 0 -200 -90 -200 -200
                                v -1652 c 0 -110 90 -200 200 -200 h 1067 c 110 0 200 90 200 200 V 1852.5 z">
                            <GeometryDrawing.Pen>
                                <Pen Brush="#000000" />
                            </GeometryDrawing.Pen>
                        </GeometryDrawing>
                        <GeometryDrawing
                            Brush="{StaticResource RadialGradientBrushKey}"
                            Geometry="M 1080.5 1402.5 c 0 110 -90 200 -200 200 h -293 c -110 0 -200 -90 -200 -200 v -797
                                c 0 -110 90 -200 200 -200 h 293 c 110 0 200 90 200 200 V 1402.5 z" />
                        <GeometryDrawing
                            Geometry="M 1080.5 1402.5 c 0 110 -90 200 -200 200 h -293 c -110 0 -200 -90 -200 -200 v -797
                                c 0 -110 90 -200 200 -200 h 293 c 110 0 200 90 200 200 V 1402.5 z">
                            <GeometryDrawing.Pen>
                                <Pen Brush="#636bc1" Thickness="27" />
                            </GeometryDrawing.Pen>
                        </GeometryDrawing>
                        <GeometryDrawing
                            Brush="#ff0000"
                            Geometry="M 156.398 76.5 h 64.75 L 307.5 337.242 c 4.664 13.766 8.813 22.25 12.453 25.453
                                c 3.633 3.203 10.313 4.805 20.047 4.805 v 47 H 204 v -47l8.266 -0.242 c 7.57 0 12.867 -1.164 15.898 -3.5
                                c 3.023 -2.328 4.539 -5.188 4.539 -8.578 c 0 -2.891 -1.305 -8.852 -3.914 -17.867 l -8.742 -30.813 h -87.266
                                l -10.766 34.133 c -2.203 7.266 -3.297 12.023 -3.297 14.281 c 0 2.586 0.781 4.93 2.359 7.023
                                s 4.141 3.625 7.688 4.594 c 2.313 0.648 8.727 0.969 19.234 0.969 v 47 H 37 v -47
                                c 7.125 0 12.328 -0.727 15.617 -2.18 s 5.992 -3.641 8.117 -6.555 c 2.125 -2.906 4.484 -8.328 7.094 -16.25
                                L 156.398 76.5 z M 147.914 258.5 h 57.188 l -27.914 -92.875 L 147.914 258.5 z" />
                        <GeometryDrawing
                            Brush="#ff0000"
                            Geometry="M 1311.602 1976.5 h -64.75 l -86.352 -260.742 c -4.664 -13.766 -8.813 -22.25 -12.453 -25.453
                                c -3.633 -3.203 -10.313 -4.805 -20.047 -4.805 v -47 h 136 v 47 l -8.266 0.242
                                c -7.57 0 -12.867 1.164 -15.898 3.5 c -3.023 2.328 -4.539 5.188 -4.539 8.578
                                c 0 2.891 1.305 8.852 3.914 17.867 l 8.742 30.813 h 87.266 l 10.766 -34.133
                                c 2.203 -7.266 3.297 -12.023 3.297 -14.281 c 0 -2.586 -0.781 -4.93 -2.359 -7.023
                                s -4.141 -3.625 -7.688 -4.594 c -2.313 -0.648 -8.727 -0.969 -19.234 -0.969 v -47 h 111 v 47
                                c -7.125 0 -12.328 0.727 -15.617 2.18 s -5.992 3.641 -8.117 6.555 c -2.125 2.906 -4.484 8.328 -7.094 16.25
                                L 1311.602 1976.5 z M 1320.086 1794.5 h -57.188 l 27.914 92.875 L 1320.086 1794.5 z" />
                        <GeometryDrawing
                            Brush="#ff0000"
                            Geometry="M 63.709 718.157 c -5.067 -10.677 -13.2 -26.4 -15.6 -37.2 c -7.2 -27.6 -14.4 -60 -6 -88.8
                                c 13.2 -45.6 69.6 -62.4 111.6 -44.4 c 18 7.2 27.6 26.4 32.4 45.6 c 1.2 2.4 4.8 2.4 6 0
                                c 3.6 -25.2 21.6 -46.8 45.6 -51.6 c 48 -8.4 88.8 26.4 94.8 72 c 4.8 38.4 -8.4 74.4 -27.6 108
                                c -37.2 67.2 -75.6 129.6 -116.4 193.2 C 140.51 854.957 97.31 788.957 63.709 718.157 z" />
                        <GeometryDrawing
                            Brush="#ff0000"
                            Geometry="M 1406.117 1334.843 c 5.066 10.677 13.199 26.4 15.6 37.199 c 7.199 27.601 14.4 60 6 88.801
                            c -13.2 45.6 -69.6 62.399 -111.6 44.4 c -18 -7.201 -27.601 -26.4 -32.4 -45.601 c -1.2 -2.399 -4.801 -2.399 -6 0
                            c -3.6 25.2 -21.6 46.8 -45.6 51.601 c -48 8.399 -88.801 -26.4 -94.801 -72 c -4.8 -38.4 8.4 -74.4 27.6 -108
                            c 37.201 -67.201 75.601 -129.601 116.4 -193.2 C 1329.316 1198.042 1372.517 1264.042 1406.117 1334.843 z" />
                        <GeometryDrawing
                            Brush="#ffffff"
                            Geometry="M 486.919 985.813 c -10.134 -21.355 -26.4 -52.8 -31.2 -74.4 c -14.4 -55.2 -28.8 -120 -12 -177.6
                                c 26.4 -91.2 139.2 -124.8 223.2 -88.8 c 36 14.4 55.199 52.8 64.801 91.2 c 2.398 4.8 9.6 4.8 12 0
                                c 7.199 -50.4 43.199 -93.6 91.199 -103.2 c 96 -16.8 177.6 52.8 189.6 144 c 9.6 76.8 -16.799 148.8 -55.199 216
                                c -74.4 134.4 -151.201 259.2 -232.801 386.4 C 640.519 1259.413 554.119 1127.413 486.919 985.813 z">
                            <GeometryDrawing.Pen>
                                <Pen
                                    Thickness="27"
                                    Brush="#ff0000" />
                            </GeometryDrawing.Pen>
                        </GeometryDrawing>
                    </DrawingGroup.Children>
                </DrawingGroup>
            </DrawingImage.Drawing>
        </DrawingImage>
    </Window.Resources>
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"   />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0"
            HorizontalAlignment="Center"
            Margin="0 0 0 10">
            <Bold>비트맵</Bold>
        </TextBlock>
        <library:ImageColorPicker x:Name="picker1" Grid.Row="1" Grid.Column="0"
            Source="IMAGE/source.png" />
        <Border Grid.Row="2" Grid.Column="0"
            HorizontalAlignment="Center"
            Margin="10"
            Width="50"
            Height="50"
            BorderThickness="1"
            BorderBrush="Black">
            <Rectangle
                Fill="{Binding ElementName=picker1,
                    Path=SelectedColor,
                    Converter={StaticResource ColorToSolidColorBrushConverterKey}}" />
        </Border>
        <TextBlock Grid.Row="0" Grid.Column="1"
            HorizontalAlignment="Center"
            Margin="0 0 0 10">
            <Bold>드로잉</Bold>
        </TextBlock>
        <library:ImageColorPicker x:Name="picker2" Grid.Row="1" Grid.Column="1"
            Source="{StaticResource DrawingImageKey}" />
        <Border Grid.Row="2" Grid.Column="1"
            HorizontalAlignment="Center"
            Margin="10"
            Width="50"
            Height="50"
            BorderBrush="Black"
            BorderThickness="1">
            <Rectangle
                Fill="{Binding ElementName=picker2,
                    Path=SelectedColor,
                    Converter={StaticResource ColorToSolidColorBrushConverterKey}}" />
        </Border>
    </Grid>
</Window>

 

300x250

 

[TestProject2 프로젝트]

 

▶ MainWindow.xaml

<Window x:Class="TestProject2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:library="clr-namespace:TestLibrary;assembly=TestLibrary"
    Width="800"
    Height="600"
    Title="Image 클래스 : 이미지 색상 선택기 사용하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Window.Resources>
        <library:ColorToSolidColorBrushConverter x:Key="ColorToSolidColorBrushConverterKey" />
    </Window.Resources>
    <DockPanel>
        <Menu DockPanel.Dock="Top"
            FontFamily="나눔고딕코딩"
            FontSize="16"
            Padding="10">
            <MenuItem Header="파일 (_F)">
                <MenuItem Header="열기 (_O)"
                    Click="openMenuItem_Click" />
                <MenuItem Header="종료 (_E)"
                    Click="exitMenuItem_Click" />
            </MenuItem>
        </Menu>
        <Grid Margin="10">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"    />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <library:ImageColorPicker x:Name="picker" Grid.Row="0"
                Source="IMAGE/source.png" />
            <Border Grid.Row="1"
                HorizontalAlignment="Center"
                Margin="10"
                Width="50"
                Height="50"
                BorderThickness="1"
                BorderBrush="Black">
                <Rectangle
                    Fill="{Binding ElementName=picker,
                        Path=SelectedColor,
                        Converter={StaticResource ColorToSolidColorBrushConverterKey}}" />
            </Border>
        </Grid>
    </DockPanel>
</Window>

 

▶ MainWindow.xaml.cs

using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Media.Imaging;

namespace TestProject2
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 열기 메뉴 항목 클릭시 처리하기 - openMenuItem_Click(sender, e)

        /// <summary>
        /// 열기 메뉴 항목 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void openMenuItem_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if(openFileDialog.ShowDialog() == true)
            {
                try
                {
                    this.picker.Source = new BitmapImage(new Uri(openFileDialog.FileName));
                }
                catch(Exception exception)
                {
                    MessageBox.Show(this, "ERROR", exception.Message);
                }
            }
        }

        #endregion
        #region 종료 메뉴 항목 클릭시 처리하기 - exitMenuItem_Click(sender, e)

        /// <summary>
        /// 종료 메뉴 항목 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void exitMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요