如何在C#中绘制图像

时间:2013-03-20 00:54:30

标签: c# wpf image

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

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

3 个答案:

答案 0 :(得分:5)

好的,这是我对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);

        }
    }

视图模型:

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

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

enter image description here

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

推荐的WPF方法是使用MVVM并理解UI is Not Data

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

enter image description here

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

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

答案 1 :(得分:0)

答案 2 :(得分: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;