如何在C#中绘制图像 [英] How to Draw an Image in C#

查看:157
本文介绍了如何在C#中绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用WPF的C#中,如何绘制图像?我尝试在线搜索,但我似乎找到的所有教程都涉及绘制形状或设置背景图像

In C# with WPF, how do I draw an Image? I have tried searching online, but all the tutorials I seem to find deal with drawing a shape, or setting a background Image.

我有兴趣尝试创建国际象棋程序。我将电路板设置为背景图像,但无法弄清楚如何为图像绘制图像。

I am interested in trying to create a chess program. I have the board set as the background Image, but cannot figure out how to draw images for the pieces.

推荐答案

好的,这是我对ChessBoard的看法:

Ok, this is my take on a ChessBoard:

<Window x:Class="MiscSamples.ChessBoard"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MiscSamples"
        Title="ChessBoard" Height="300" Width="300">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:ChessPiece}">
            <Image Source="{Binding ImageSource}"/>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <UniformGrid Rows="8" Columns="8" Opacity=".5">
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>

            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>

            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>

            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>

            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>

            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>

            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>

            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>
            <Rectangle Fill="Black"/>
            <Rectangle Fill="White"/>

        </UniformGrid>

        <ItemsControl ItemsSource="{Binding}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid IsItemsHost="True">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                    </Grid>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Grid.Row" Value="{Binding Row}"/>
                    <Setter Property="Grid.Column" Value="{Binding Column}"/>
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Window>

代码背后:

using System.Linq;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace MiscSamples
{
    public partial class ChessBoard : Window
    {
        public ObservableCollection<ChessPiece> Pieces { get; set; }

        public ChessBoard()
        {
            Pieces = new ObservableCollection<ChessPiece>();
            InitializeComponent();
            DataContext = Pieces;
            NewGame();
        }

        private void NewGame()
        {
            Pieces.Clear();
            Pieces.Add(new ChessPiece() { Row = 0, Column = 0, Type = ChessPieceTypes.Tower, IsBlack = true});
            Pieces.Add(new ChessPiece() { Row = 0, Column = 1, Type = ChessPieceTypes.Knight, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 2, Type = ChessPieceTypes.Bishop, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 3, Type = ChessPieceTypes.Queen, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 4, Type = ChessPieceTypes.King, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 5, Type = ChessPieceTypes.Bishop, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 6, Type = ChessPieceTypes.Knight, IsBlack = true });
            Pieces.Add(new ChessPiece() { Row = 0, Column = 7, Type = ChessPieceTypes.Tower, IsBlack = true });

            Enumerable.Range(0, 8).Select(x => new ChessPiece()
                {
                    Row = 1, 
                    Column = x, 
                    IsBlack = true, 
                    Type = ChessPieceTypes.Pawn
                }).ToList().ForEach(Pieces.Add);


            Pieces.Add(new ChessPiece() { Row = 7, Column = 0, Type = ChessPieceTypes.Tower, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 1, Type = ChessPieceTypes.Knight, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 2, Type = ChessPieceTypes.Bishop, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 3, Type = ChessPieceTypes.Queen, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 4, Type = ChessPieceTypes.King, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 5, Type = ChessPieceTypes.Bishop, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 6, Type = ChessPieceTypes.Knight, IsBlack = false });
            Pieces.Add(new ChessPiece() { Row = 7, Column = 7, Type = ChessPieceTypes.Tower, IsBlack = false });

            Enumerable.Range(0, 8).Select(x => new ChessPiece()
            {
                Row = 6,
                Column = x,
                IsBlack = false,
                Type = ChessPieceTypes.Pawn
            }).ToList().ForEach(Pieces.Add);

        }
    }

ViewModel:

ViewModel:

    public class ChessPiece: INotifyPropertyChanged
    {
        public bool IsBlack { get; set; }

        public ChessPieceTypes Type { get; set; }


        private int _row;
        public int Row
        {
            get { return _row; }
            set
            {
                _row = value;
                OnPropertyChanged("Row");
            }
        }

        private int _column;
        public int Column
        {
            get { return _column; }
            set
            {
                _column = value;
                OnPropertyChanged("Column");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public string ImageSource 
        {
            get { return "../ChessPieces/" + (IsBlack ? "Black" : "White") + Type.ToString() + ".png"; }
        }
    }

    public enum ChessPieceTypes
    {
        Pawn,
        Tower,
        Knight,
        Bishop,
        Queen,
        King,
    }
}

这就是我的电脑里的样子:

This is what it looks like in my computer:

请注意我使用纯XAML来创建UI。绝不是我在代码中创建或操纵UI元素。 WPF不需要它,也不建议使用它。

Please notice that I'm using pure XAML to create the UI. In no way Im creating nor manipulating UI elements in code. WPF doesn't need that, and it's also not recommended.

推荐的WPF方法是使用 MVVM 并了解 UI是不是数据

The recommended approach to WPF is to use MVVM and understand that UI is Not Data

您可以将我的代码复制并粘贴到文件 - >新项目 - > WPF应用程序并亲自查看结果。您将需要以下项目结构:

You can copy and paste my code in a File -> New Project -> WPF Application and see the results for yourself. You will need the following project structure:

另请注意,图像文件需要设置为构建操作:资源

Also note that the Image files need to be set to Build Action: Resource.

请记住:这是一切的WPF方法 。您很少需要在WPF中的代码中操作UI元素,或者执行绘图或其他类似的操作。

Remember: This is the WPF approach to EVERYTHING. You rarely have to manipulate UI elements in code in WPF, or do things such as drawing or anything like that.

这篇关于如何在C#中绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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