在Flutter中,我想将RGB颜色作为MaterialColor()构造函数中的int主色。如何将RGB值转换为十六进制整数,其格式为:0xff ------?抱歉,这个简短的问题,我真的在任何地方都找不到!

最佳答案

您可以使用以下功能将RGB转换为十六进制,

int hexOfRGBA(int r,int g,int b,{double opacity=1})
    {
          r = (r<0)?-r:r;
          g = (g<0)?-g:g;
          b = (b<0)?-b:b;
          opacity = (opacity<0)?-opacity:opacity;
          opacity = (opacity>1)?255:opacity*255;
          r = (r>255)?255:r;
          g = (g>255)?255:g;
          b = (b>255)?255:b;
          int a = opacity.toInt();
          return int.parse('0x${a.toRadixString(16)}${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');
    }

用法:
    Color(hexOfRGBA(0,0,0,opacity: 0.7));


但是出于某种原因,如果您想保持用例特定,


int hexOfRGB(int r,int g,int b)
    {
      r = (r<0)?-r:r;
      g = (g<0)?-g:g;
      b = (b<0)?-b:b;
      r = (r>255)?255:r;
      g = (g>255)?255:g;
      b = (b>255)?255:b;
      return int.parse('0xff${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');
    }

用法:
Color(hexOfRGB(255,255,255));


   int hexOfRGBA(int r,int g,int b,double opacity)
        {
         r = (r<0)?-r:r;
          g = (g<0)?-g:g;
          b = (b<0)?-b:b;
          opacity = (opacity<0)?-opacity:opacity;
          opacity = (opacity>1)?255:opacity*255;
          r = (r>255)?255:r;
          g = (g>255)?255:g;
          b = (b>255)?255:b;
          int a = opacity.toInt();
          return int.parse('0x${a.toRadixString(16)}${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');
        }

用法:
Color(hexOfRGBA(0,0,0,0.7));

09-04 22:41