这段代码支持的Web颜色格式为 #RRGGBB/#RGB 以及以Web标准名称命名的颜色(需要引用单元:qstring,graphutil):
function ParseWebColor(S: String;ADefColor:TColor=clBlack): TColor;
var
p: PChar;
c: array [0 .. 3] of Byte absolute Result;
i: Integer;
begin
Result := 0;
p := PChar(S);
i := 0;
if p^ in ['a' .. 'z', 'A' .. 'Z'] then
begin
if IdentToColor('cl' + S, i) then
Result := i
else
begin
S := 'clWeb' + S;
for I := 0 to High(WebNamedColors) do
begin
if CompareText(WebNamedColors[I].Name, S) = 0 then
begin
Result := WebNamedColors[I].Value;
Exit;
end;
end;
Result := ADefColor;
end;
Exit;
end
else if p^ = '#' then
begin
Inc(p);
if Length(S) = 4 then // #RGB
begin
while p^ <> #0 do
begin
if IsHexChar(p^) then
begin
c[i] := (HexValue(p^) * 255) div 15;
Inc(i);
Inc(p);
end
else
break;
end;
end
else if Length(S) = 7 then
begin
while p^ <> #0 do
begin
if IsHexChar(p^) then
begin
c[i] := HexValue(p^);
Inc(p);
if p^ <> #0 then
begin
c[i] := (c[i] shl 4) + HexValue(p^);
Inc(p);
end;
Inc(i);
end
else
break;
end;
end;
end;
if i <> 3 then
Result := ADefColor;
end;
比如#FF0000 和 #F00 都被解释为红色。
