こんにちは、私は砂漠の果ての狼です。

前几天刚上线一个颜色值转换工具,当然这是借鉴的,可实现:
- HEX、RGB、RGBA、ARGB、HSL間の相互変換;
- HTMLとCSSのカラー仕様で定義されている147の色名(17の標準色と130のその他の色)を開発中に見つけるための非常に便利なCSSカラーテーブルを示しています。

この記事では、このツールを開発する際に、関連するJSコードとC#コードの翻訳と比較を簡単に列挙し、同様の開発参照をフォローアップしやすくします。
JS文件:点这
- カラー値HEX変換
提取HEX#9A3B34中R(Red)、G(Green)、B(Blue)的色值。
JSコードです
function parseHEX(val) {
let color = new Color();
try {
let rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
let hex = val.replace(rgx, function (m, r, g, b) {
return r + r + g + g + b + b;
});
let rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
color.r = parseInt(rgb[1], 16);
color.g = parseInt(rgb[2], 16);
color.b = parseInt(rgb[3], 16);
} catch (e) {
console.log(e)
}
return color;
}
C#のコード
public static Color? ParseHEX(string hexColor)
{
hexColor = hexColor.TrimStart('#');
Regex regex = new(@"^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$");
var match = regex.Match(hexColor);
if (match?.Success == true)
{
int red = Convert.ToInt32(match.Groups[1].Value, 16);
int green = Convert.ToInt32(match.Groups[2].Value, 16);
int blue = Convert.ToInt32(match.Groups[3].Value, 16);
return new Color(red, green, blue);
}
else
{
return null;
}
}
2. カラー値RGBA変換
変換ロジックは基本的に同じです。
JSコードです
function parseRGBA(val) {
let color = new Color();
try {
let rgba = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/.exec(val);
color.r = parseInt(rgba[1]);
color.g = parseInt(rgba[2]);
color.b = parseInt(rgba[3]);
color.a = parseFloat(rgba[4] || 1);
} catch (e) {
console.log(e)
}
return color;
}
C#のコード
public static Color? ParseRGBA(string color)
{
Regex regex = new Regex(@"^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$");
var match = regex.Match(color);
if (match?.Success == true)
{
int r = int.Parse(match.Groups[1].Value);
int g = int.Parse(match.Groups[2].Value);
int b = int.Parse(match.Groups[3].Value);
if (!double.TryParse(match.Groups[4].Value, out double a))
{
a = 1;
}
return new Color(r, g, b, a);
}
return null;
}
chatGPTを介して、JSコードをC#コードに簡単に翻訳することができ、Blazorツールを迅速に行うことができ、他のオンラインプログラミング言語翻訳サイトは理想的ではなく、より多くの状況が手動で変更する必要があります。
- 本工具地址:Blazor Server版, Blazor Wasm版
- 网站源码及Issue:源码,Issue
- .NET版本: .NET 8.0.0-preview.5.23280.8
- WeChat技術グループ:ウェブマスター WeChat(codewf)を追加し、“グループに入る”2つの単語をメモしてください
- QQ技術グループ:77 1992,30 0