vb.net 将十六进制颜色字符串转换为 RGB 颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13356486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:25:29  来源:igfitidea点击:

Convert hex color string to RGB color

vb.netwinforms

提问by Nh123

I want to convert hex color to RGB color.

我想将十六进制颜色转换为 RGB 颜色。

I used the following code:

我使用了以下代码:

Me.BackColor = RGB("#000000")

But then it throws the following exception:

但随后它抛出以下异常:

Argument not specified for parameter 'Green' of 'Public Function RGB(Red As Integer, Green As Integer, Blue As Integer) As Integer'

What is the right way to do it?

正确的做法是什么?

回答by famf

By ColorTranslator:

通过 ColorTranslator:

ColorTranslator.FromHtml("#003399") 

Other Ways:

其他方法:

Public Function ConvertToRbg(ByVal HexColor As String) As Color
    Dim Red As String
    Dim Green As String
    Dim Blue As String
    HexColor = Replace(HexColor, "#", "")
    Red = Val("&H" & Mid(HexColor, 1, 2))
    Green = Val("&H" & Mid(HexColor, 3, 2))
    Blue = Val("&H" & Mid(HexColor, 5, 2))
    Return Color.FromArgb(Red, Green, Blue)
End Function

or:

或者:

Public Shared Function HexToColor(ByVal hexColor As String) As Color
    If hexColor.IndexOf("#"c) <> -1 Then
        hexColor = hexColor.Replace("#", "")
    End If
    Dim red As Integer = 0
    Dim green As Integer = 0
    Dim blue As Integer = 0
    If hexColor.Length = 6 Then
        red = Integer.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier)
    ElseIf hexColor.Length = 3 Then
        red = Integer.Parse(hexColor(0).ToString() + hexColor(0).ToString(), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor(1).ToString() + hexColor(1).ToString(), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor(2).ToString() + hexColor(2).ToString(), NumberStyles.AllowHexSpecifier)
    End If
    Return Color.FromArgb(red, green, blue)
End Function

or:

或者:

    Dim c As String = "#ffffff"
    c = Replace(c, "#", "")
    c = "&H" & c
    ColorTranslator.FromOle(c)

or:

或者:

Public Function hexToRbgNew(ByVal Hex As String) As Color
    Hex = Replace(Hex, "#", "")
    Dim red As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, red, "", , 1)
    Dim green As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, green, "", , 1)
    Dim blue As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, blue, "", , 1)
    Return Color.FromArgb(red, green, blue)
End Function

回答by Eduardo

This works for me: (vb.Net)

这对我有用:(vb.Net)

cell.BackColor = Drawing.Color.FromArgb(&H3399FF)