无法使colormatrix和透明度正常工作

时间:2013-03-28 08:56:57

标签: .net vb.net transparency colormatrix

我正在开发一个RTS风格的游戏,以了解有关使用类,继承和接口进行编程的更多信息 - 它运行良好,没有重大问题。

我遇到的问题是使用colormatrix。在地图上放置单位时,我使用颜色矩阵添加绿色或红色叠加,具体取决于位置的有效性。使用以下代码再次正常工作(为清晰起见,将其删除)。但我也想让图像半透明。

这是我正在使用的代码,它首先使单位灰度,然后将其着色为红色,但不使其半透明。

Public Overrides Function GetCurrentFrame() As Image
    _AnimationFrame += _AnimationFrameTime
    If _AnimationFrame > 5 Then _AnimationFrame = 0
    Dim CurrentFrame As Image = Nothing

    CurrentFrame = My.Resources.ResourceManager.GetObject("dragoon_walk_l_" & Convert.ToInt16(_AnimationFrame).ToString)

    Dim g As Graphics = Graphics.FromImage(CurrentFrame)

    Dim cm As System.Drawing.Imaging.ColorMatrix = New System.Drawing.Imaging.ColorMatrix(New Single()() _
         {New Single() {0.3, 0.3, 0.3, 0, 0}, _
        New Single() {0.59, 0.59, 0.59, 0, 0}, _
        New Single() {0.11, 0.11, 0.11, 0, 0}, _
        New Single() {0, 0, 0, 1, 0}, _
        New Single() {0.5, 0, 0, 0.5, 1}})

    Dim ia As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes()
    ia.SetColorMatrix(cm)
    g.DrawImage(CurrentFrame, New Rectangle(0, 0, CurrentFrame.Width, CurrentFrame.Height), 0, 0, CurrentFrame.Width, CurrentFrame.Height, GraphicsUnit.Pixel, ia)

    g.DrawImage(My.Resources.ResourceManager.GetObject("health" & (Int(20 * (_UnitHealth / _UnitHealthMax)) - 1).ToString), 0, 14)
    g.DrawImage(My.Resources.ResourceManager.GetObject("level" & _Level.ToString), 6, 0)
    g.Dispose()
    Return CurrentFrame
End Function

为了澄清,问题是如何使用彩色矩阵将我的图像变为红色和半透明。

1 个答案:

答案 0 :(得分:0)

现在已经看了2天了,它刚刚来找我。

问题是我是从原始图像创建位图,而不是空白位图。并返回图像而不是位图:(

这是我使用的解决方案

Public Overrides Function GetCurrentFrame() As Image
    _AnimationFrame += _AnimationFrameTime
    If _AnimationFrame > 5 Then _AnimationFrame = 0
    Dim CurrentFrame As Image = Nothing

    CurrentFrame = My.Resources.ResourceManager.GetObject("dragoon_walk_l_" & Convert.ToInt16(_AnimationFrame).ToString)

    Dim bm As Bitmap = New Bitmap(CurrentFrame.Width, CurrentFrame.Height)
    Dim g As Graphics = Graphics.FromImage(bm)

    Dim cm As System.Drawing.Imaging.ColorMatrix = New System.Drawing.Imaging.ColorMatrix(New Single()() _
         {New Single() {.3, .3, .3, 0, 0}, _
        New Single() {0.59, .59,.59, 0, 0}, _
        New Single() {.1, 0.1, 0.1, 0, 0}, _
        New Single() {0, 0, 0, 0.75, 0}, _
        New Single() {0.5, 0, 0, 0, 1}})

    Dim ia As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes()
    ia.SetColorMatrix(cm)
    g.DrawImage(CurrentFrame, New Rectangle(0, 0, CurrentFrame.Width, CurrentFrame.Height), 0, 0, CurrentFrame.Width, CurrentFrame.Height, GraphicsUnit.Pixel, ia)

    g.DrawImage(My.Resources.ResourceManager.GetObject("health" & (Int(20 * (_UnitHealth / _UnitHealthMax)) - 1).ToString), 0, 14)
    g.DrawImage(My.Resources.ResourceManager.GetObject("level" & _Level.ToString), 6, 0)
    g.Dispose()
    Return bm
End Function