0

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

我有兴趣尝试创建一个国际象棋程序。我将棋盘设置为背景Image,但不知道如何为棋子绘制图像。

4

3 回答 3

7

好的,这是我对棋盘的看法:

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

        }
    }

视图模型:

    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,
    }
}

这是它在我的电脑中的样子:

在此处输入图像描述

请注意,我使用纯 XAML 来创建 UI。我绝不会在代码中创建或操作 UI 元素。WPF 不需要,也不推荐。

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

您可以将我的代码复制并粘贴到 a 中File -> New Project -> WPF Application,然后自己查看结果。您将需要以下项目结构:

在此处输入图像描述

另请注意,图像文件需要设置为Build Action: Resource.

请记住:这是 WPF 的EVERYTHING. 您很少需要在 WPF 中的代码中操作 UI 元素,或者执行诸如绘图之类的事情。

于 2013-03-20T01:54:11.067 回答
0

这取决于你想怎么画我通常使用位图,这就是我这样做的方式。

//Initialize image and stuff
int Width = 100;
int Height = 100;
int nStride = (Width * PixelFormats.Bgra32.BitsPerPixel + 7) / 8;
Int32Rect ImageDimentions = new Int32Rect(0, 0, Width, Height);
int[] ImageArr = new ImageArr[Height * nStride];

//Manually paint your image
for (int Y = 0; Y < Height; Y++)
{
    for (int X = 0; X < Width; X++)
    {
       //X and Y means pixel(X,Y) in cartesian plane 1 quadrant mirrored around X axis
       //Down is the Y from 0 to height, and right to left is X from 0 to width
       int index = (Y * Width + X) * 4;
       ImageArr[index + 0] = (byte)0;   //Blue
       ImageArr[index + 1] = (byte)0;   //Green
       ImageArr[index + 2] = (byte)0;   //Red
       ImageArr[index + 3] = (byte)255; //Alpha
    }
}

//Push your data to a Bitmap
WriteableBitmap BmpToWriteOn = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgra32, null);
BmpToWriteOn.WritePixels(ImageDimentions, ImageArr, nStride, 0, 0);     

//Push your bitmap to Xaml Image
YourXamlImage.Source = BmpToWriteOn;
于 2013-03-20T02:22:55.113 回答
0

对于位图,您可以使用BitmapImage

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

于 2013-03-20T00:57:59.223 回答