如何动态加载MetroUI中的BitmapImage

时间:2011-10-19 14:40:03

标签: vb.net windows-8 microsoft-metro bitmapimage imagebrush

我一直在尝试使用Windows 8和Metro UI,我已经编写了一个完全合理的位图图像加载,但它似乎没有加载,任何帮助都表示赞赏。

Public Sub New(Image As String)

Debug.Print("ms-resource://MyAssembly/" & Image)


Img = New ImageBrush()
Dim Bitmap As New BitmapImage()
Bitmap.UriSource = New Uri("ms-resource://MyAssembly/" & Image, UriKind.Absolute)

Img.ImageSource = Bitmap
Width = Bitmap.PixelWidth
Height = Bitmap.PixelHeight

Debug.Print("Height: " & Height & " Width: " & Width)

End Sub

在此示例中,“宽度”和“高度”始终取值为零。 它在同一个类中呈现..

    Public Sub Render(X As Integer, Y As Integer, Canv As Canvas)

        Dim Sprite As New Shapes.Rectangle
        Sprite.Width = CDbl(Width)
        Sprite.Height = CDbl(Height)
        Sprite.Fill = Img
        Sprite.SetValue(Canvas.TopProperty, CDbl(Y))
        Sprite.SetValue(Canvas.LeftProperty, CDbl(X))
        Canv.Children.Add(Sprite)

    End Sub

End Class

以下是创建/调用的地方:

V = New Sprite("Images/Test.bmp")
gameRoot.Children.Clear()
V.Render(100, 100, gameRoot)

===

我的canvas对象不是问题,因为如果我用Sprite.Fill = New SolidColorBrush(Colors.White)填充它然后它工作正常,我在屏幕上看到一个白色方块,所讨论的位图设置为“始终复制” “,当我查看它时,它位于目标文件夹中。

我不太确定我做错了什么。

1 个答案:

答案 0 :(得分:0)

我自己设法解决了这个问题。

你可以通过使用来获得基础uri Me.Uri;或者在C#This.Uri。

这是完成的代码,可以让任何人将位图图像加载到画布中;甚至旋转它。

我自己写了这个,所以任何发现它有同样问题的人都可以随意使用它。

图片必须采用“FilePath / Image.extension”格式

Public Class Sprite

    'Public Shared Baseuri As Uri

    Public Img As ImageBrush
    Public Bitmap As BitmapImage

    Public Sub New(Image As String, Base As Uri)

        'Debug.Print("BASE:" & Base.ToString)
        'Debug.Print("USING:" & Image)
        'Debug.Print("RESULT:" & New Uri(Base, Image).ToString)

        Img = New ImageBrush()
        Bitmap = New BitmapImage(New Uri(Base, Image))

    End Sub

    Public Overloads Sub Render(X As Integer, Y As Integer, Width As Integer, Height As Integer, Canv As Canvas)

        Img.ImageSource = Bitmap
        Dim Sprite As New Shapes.Rectangle
        Sprite.Width = CDbl(Width)
        Sprite.Height = CDbl(Height)
        Sprite.Fill = Img
        Sprite.SetValue(Canvas.TopProperty, CDbl(Y))
        Sprite.SetValue(Canvas.LeftProperty, CDbl(X))
        Canv.Children.Add(Sprite)

    End Sub

    Public Overloads Sub Render(X As Integer, Y As Integer, Width As Integer, Height As Integer, Canv As Canvas, Angle As Integer)

        Img.ImageSource = Bitmap
        Dim Sprite As New Shapes.Rectangle
        Sprite.Width = CDbl(Width)
        Sprite.Height = CDbl(Height)
        Sprite.Fill = Img
        Sprite.SetValue(Canvas.TopProperty, CDbl(Y))
        Sprite.SetValue(Canvas.LeftProperty, CDbl(X))

        Dim v As New Windows.UI.Xaml.Media.RotateTransform
        v.Angle = CDbl(Angle)
        v.CenterX = Width / 2
        v.CenterY = Height / 2
        Sprite.RenderTransform = v


        Canv.Children.Add(Sprite)

    End Sub

End Class