开发者

Creating listview icons on the fly on VB.NET?

Is that possible? I want to pass my custom color as a parameter and I want to receive an Image (rectangle for example).

Public Function createIcon(ByVal c As Color) As Bitmap
    Dim g As Graphics
    Dim开发者_StackOverflow社区 Brush As New SolidBrush(c)
    g.FillRectangle(Brush, New Rectangle(0, 0, 20, 20))
    Dim bmp As New Bitmap(20, 20, g)
    Return bmp
End Function

I tried this way and couldn't success.


  • Bitmap: A canvas (in memory) that contains an image.
  • Graphics: A tool set that allows you to draw on an associated canvas.

With this in mind, here is the solution:

Public Function CreateIcon(ByVal c As Color, ByVal x As Integer, ByVal y As Integer) As Bitmap
    Dim icon As New Bitmap(x, y)

    Using g = Graphics.FromImage(icon)
        Using b As New SolidBrush(c)
            g.FillRectangle(b, New Rectangle(0, 0, 20, 20))
        End Using
    End Using

    Return icon
End Function

The Using blocks here merely serve the purpose of disposing the graphics resources properly (by automatically calling their Dispose method at the end of the block). You need to do this, otherwise you will leak graphics resources.


Okay, got it. I am going to share what I did just in case.

Public Function createIcon(ByVal c As Color, ByVal x As Integer, ByVal y As Integer) As Bitmap
    createIcon = New Bitmap(x, y)
    For i = 0 To x - 1
        For j = 0 To y - 1
            If i = 0 Or j = 0 Or i = x - 1 Or j = y - 1 Then
                createIcon.SetPixel(i, j, Color.Black)
            Else
                createIcon.SetPixel(i, j, c)
            End If
        Next
    Next
    Return createIcon
End Function

This function will give you a colored rectangle with black border.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜