【问题标题】:Tiling image in WPFWPF中的平铺图像
【发布时间】:2017-06-18 08:42:58
【问题描述】:

我正在开发一个游戏引擎,现在我正在尝试将我的一些图像平铺而不是拉伸。

  1. 由于某种原因,图像被拉伸而不是平铺。这是我的代码:

            string filename = "mario_right.png";
            BitmapImage bim = new BitmapImage(new Uri(@"pack://application:,,,/Assets/img/" + filename));
    
            ImageBrush imgBrush = new ImageBrush();
            imgBrush.TileMode = TileMode.Tile; //this is what makes the image tiled.
                                               //You can change the imgBrush to some other modes as well.
            imgBrush.ImageSource = bim;
            player.rect.Fill = imgBrush;       //player is a Body (my own class), which inherits from the Rectangle class.
    

实际的 .png 文件为 50*50 像素。当我设置播放器的正确高度和宽度 (50*50) 时,填充图像看起来不错。 当我将高度更改为 250 像素时,我希望得到五个马里奥图像彼此重叠,但由于某种原因,这不会发生 - .png 只是被拉伸了。

(为玩家拉伸.png只是为了测试;代码实际上是用于超级马里奥类游戏中的石块。)

  1. 在测试时,我还尝试在 .xaml 文件中插入一个矩形,然后用 img 填充它。由于某种原因,我仍然无法让 Tile 工作!我尝试了四种 Stretch 变体,但无济于事:

    <Grid x:Name="LayoutRoot" Background="White">
        <Rectangle x:Name="rect" Width="50" Height="250">
            <Rectangle.Fill>
                <ImageBrush ImageSource="Assets/img/mario_right.png" TileMode="Tile" Stretch="None"/>
            </Rectangle.Fill>
        </Rectangle> 
    

(Uniform、None 等给出不同的结果,但它们都没有平铺图像。)

3。 最后,我尝试对 Grid 背景做同样的事情。再一次,图像只出现了一个,被拉伸,而不是 50*50 像素,它填满了整个窗口。

我开始认为问题与 MainWindow.xaml 文件的设置有关,但如果是这样,我该如何缩放窗口(即最大化)并相应地渲染图像?

谢谢!

彼得

【问题讨论】:

标签: wpf image


【解决方案1】:

为了平铺您的图像,您必须定义要平铺的尺寸(以像素为单位)。你需要的属性是ViewportUnitsViewport(看看here

所以你的代码应该是

ImageBrush imgBrush = new ImageBrush();
imgBrush.TileMode = TileMode.Tile;
imgBrush.ImageSource = bim;
imgBrush.ViewportUnits = BrushMappingMode.Absolute;
imgBrush.Viewport = new Rect(0, 0, 50, 50);

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2011-02-16
    • 2018-08-11
    • 2023-03-10
    相关资源
    最近更新 更多