Flutter convert Color to hex string - dart

How can I convert a flutter Color class instance into a hex string?
For example, I would like to convert Colors.blue to what would be '#4286f4'.
Usecase is letting the user choose a color and save it in the database as a hex color.
I have checked related questions and they are for converting the other way around.

You can convert the value property (includes alpha) or the individual red, green, and blue properties to Hex using int.toRadixString(16):
var myColor = Colors.blue;
var hex = '#${myColor.value.toRadixString(16)}';

This is what I'm using:
extension ColorX on Color {
String toHexTriplet() => '#${(value & 0xFFFFFF).toRadixString(16).padLeft(6, '0').toUpperCase()}';
}
Sample outputs: #00FFFF or #FF69B4
This code also makes sure that alpha is omitted (#bakua's comment)
Some Flutter source code inspiration: util.dart, painting.dart

You can add an extension to Color class to get HexString from the Color object itself directly.
extension HexColor on Color {
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${alpha.toRadixString(16).padLeft(2, '0')}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}';
}
Color color = Colors.blue ;
print(color.toHex());

This is my favorite way of handling color to string conversions. I use this really simple extension class.
extension HexColor on Color {
/// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
static Color fromHex(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}'
'${alpha.toRadixString(16).padLeft(2, '0')}';
}

Though the question is converting Color to Hex, if you want to store and retrieve Color information, I've used like this.
Save color data as int. Colors.blue.value
Retrieve data as int and pass it to Color class Color(savedInt)

In flutter if AA is the alpha value in hex, RR the red value in hex, GG the green value in hex, and BB the blue value in hex, a color can be expressed as const Color(0xAARRGGBB) just remove the leading two symbols to get HEX value. RRGGBB

Improved Code:
extension HexColor on Color {
String _generateAlpha({required int alpha, required bool withAlpha}) {
if (withAlpha) {
return alpha.toRadixString(16).padLeft(2, '0');
} else {
return '';
}
}
String toHex({bool leadingHashSign = false, bool withAlpha = false}) =>
'${leadingHashSign ? '#' : ''}'
'${_generateAlpha(alpha: alpha, withAlpha: withAlpha)}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}'
.toUpperCase();
}
Usage:
pickerColor.toHex(withAlpha: true);

Related

How to convert a unicode hex string into its ASCII equivalent

I hope everything is going well.
I have this unicodestring:
353135313531353135313531
And I want to transform it into another unicodestring with this content:
515151515151
In other words, convert a hex representation into its ASCII interpretation.
It is very straightforward to do this in C, but the idea is to work with C++ Builder.
This is what I have been trying to do:
String hex_to_ascii(const String& hex_str) {
String ascii_str = "";
for (int i = 1; i <= hex_str.Length(); i += 2) {
String hex_char = hex_str.SubString(i, 2);
int ascii_char = hex_char.ToInt();
// ascii_str += String().sprintf(_D("%c"), ascii_char);
ascii_str.Insert(ascii_char, ascii_str.Length() + 1);
}
return ascii_str;
But no luck so far.
I know there is a method called ToHex I've been trying to search for documentation about it because it's related to what I am trying to do, so probably the library that has this method has also something close to what I need.
If you know how to do this or where can I read about the ToHex method, please let me know. Thank you for reading.
The code you have is very close, it just needs some minor tweaks.
Most importantly, String::ToInt() WILL NOT decode hex, like you are expecting. It will convert "35" to an integer with a value of decimal 35 (NOT hex 0x35, decimal 53), and will convert "31" to an integer with a value of decimal 31 (NOT hex 0x31, decimal 49), etc.
You need to instead use Sysutils::StrToInt() with a 0x hex prefix prepended to the string value.
Try this:
String hex_to_ascii(const String& hex_str) {
String ascii_str;
for (int i = 1; i <= hex_str.Length(); i += 2) {
String hex_char = _D("0x") + hex_str.SubString(i, 2);
int ascii_char = StrToInt(hex_char);
ascii_str += static_cast<Char>(ascii_char);
}
return ascii_str;
}
Alternatively, you can use HexToBin() to decode the hex into a byte array, and then construct a UnicodeString from those bytes, eg:
String hex_to_ascii(const String& hex_str) {
TBytes bytes;
bytes.Length = hex_str.Length() / 2;
HexToBin(hex_str.c_str(), &bytes[0], bytes.Length);
return String((char*)&bytes[0], bytes.Length);
// Alternatively:
// return TEncoding::Default.GetString(bytes);
}

Get Color Name from HexColor Code Google Sheets

I have been looking for a way which can convert to HexColor into Color Name. I have searched online but no such thing is available online.
Your help will be much appreciated.
For example, how about using an external API? In this sample script, the API of The Color API is used. The sample script is as follows.
Sample script 1:
In this sample, the hex data is converted to the color name using a custom function.
Please copy and paste the following script to the script editor of Google Spreadsheet and save it. When you use this script, for example, please put a custom function of =SAMPLE("ff0000") to a cell. By this, in this case, "Red" is returned.
const SAMPLE = hex => {
const res = UrlFetchApp.fetch("https://www.thecolorapi.com/id?format=json&hex=" + hex, { muteHttpExceptions: true });
if (res.getResponseCode() == 200) {
const obj = JSON.parse(res.getContentText());
return obj.name && obj.name.value ? obj.name.value : "";
}
return "";
}
Sample script 2:
In this sample, the background colors of cells retrieved from a1Notation are converted to the color names using a custom function.
Please copy and paste the following script to the script editor of Google Spreadsheet and save it.
const SAMPLE = a1Notation =>
SpreadsheetApp.getActiveSheet().getRange(a1Notation).getBackgrounds()
.map(r => r.map(c => {
const res = UrlFetchApp.fetch("https://www.thecolorapi.com/id?format=json&hex=" + c.slice(1), { muteHttpExceptions: true });
if (res.getResponseCode() == 200) {
const obj = JSON.parse(res.getContentText());
return obj.name && obj.name.value ? obj.name.value : "";
}
return "";
}));
Testing:
When you use this script, please put the custom function of =SAMPLE("a1Notation") to a cell. The sample situation is as follows. In this sample, by =SAMPLE("A1:C3"), the background color names of "A1:C3" are retrieved.
References:
The Color API
Custom Functions in Google Sheets
map()
fetch(url, params)
If I understand correctly what you would like to do is to get the color name of a cell in text based on the Hex code of that color.
I do not think it is possible using regular formulas from Google Sheets, so as a workaround I created the following script in Google Apps Script as a sample, so you can modify it according to what you would like to do.
let hexCode = [
{
color: "indian red",
code: {
hex: "#B0171F"
},
id: 1
},
{
color: "crimson ",
code: {
hex: "#DC143C"
},
id: 2
},
];
function getColorName(input) {
var ss = SpreadsheetApp.getActiveSheet();
var range = ss.getRange('B2');
var bg = range.getBackground();
var colorIs;
for (var i = 0; i < hexCode.length; i++) {
if (colorIs = hexCode[i].code.hex.valueOf().toString().toLowerCase() === bg.valueOf()) {
return hexCode[i].color.valueOf();
}
}
}
Basically I created an array that contains the hex codes of the colors that I will be using and created a custom function so that when I call it in Google Sheets it gets the hex code of the color from the selected range and compares it to the list of colors from the array so that it returns the name of the color.
You can just modify the array adding the colors that you need using the same format and also change the range. I will also leave a screenshot so that you can see how it works.

How to capitalize each alternate character of a string?

Lets say there is a string "johngoestoschool" it should become "JoHnGoEsToScHoOl" and incase if there is a special character in between it should ignore it for example given string "jo$%##hn^goe!st#os&choo)l" answer should be "Jo$%##Hn^GoE!sT#oS&cHoO)l"
From this answer, we in order to iterate we can do:
let s = "alpha"
for i in s.characters.indices[s.startIndex..<s.endIndex]
{
print(s[i])
}
Why can't we print the value of "i" here?
When we do i.customPlaygroundQuickLook it types int 0 to int4.
So my idea is to
if (i.customPlaygroundQuickLook == 3) {
s.characters.currentindex = capitalized
}
Kindly help
This should solve your function, the hard part is just checking weather the character is letters or not, using inout and replace range would give better performance:
func altCaptalized(string: String) -> String {
var stringAr = string.characters.map({ String($0) }) // Convert string to characters array and mapped it to become array of single letter strings
var numOfLetters = 0
// Convert string to array of unicode scalar character to compare in CharacterSet
for (i,uni) in string.unicodeScalars.enumerated() {
//Check if the scalar character is in letter character set
if CharacterSet.letters.contains(uni) {
if numOfLetters % 2 == 0 {
stringAr[i] = stringAr[i].uppercased() //Replace lowercased letter with uppercased
}
numOfLetters += 1
}
}
return stringAr.joined() //Combine all the single letter strings in the array into one string
}

Avoiding formatting of DOORS object text using DXL

I am writing DXL script in which few object text has borders(like one complete row of table is copied).
I have to emphasize the "shall" word in shall.
But using findPlainText() method, it changes the formatting of object text which have borders.
Initially the objects before scripts run is:
After running the script to make "shall" word Bold, i wrote DXL script:
void Change_Shall(Object o, string objText)
{
int off=0
int len=0
string StartUpperText = ""
string FontText = ""
string StartText = ""
string FindText = ""
bool IsChanged = false
string OriginalObjText = objText
string UpperFontObjText = upper(objText)
while (findPlainText(UpperFontObjText, "SHALL", off, len, true, false))
{
StartUpperText = UpperFontObjText[0:off-1]
UpperFontObjText = UpperFontObjText[off+len:]
FindText = OriginalObjText[off:off+len-1]
StartText = OriginalObjText[0:off-1]
OriginalObjText = OriginalObjText[off+len:]
if(FontText == "")
FontText = StartText "{\\b " FindText "}"
else
FontText = FontText StartText "{\\b " FindText "}"
//print FindText "\t\t" UpperFontObjText "\n"
IsChanged = true
off = 0
len = 0
}
if(IsChanged == true)
o."Object Text" = richText FontText OriginalObjText
}
The object text with border after this script runs get changes like
How can formatting of object text with borders be avoided and border is preserved in the object text.
I'm not sure how you're getting "Object Text" from Object o, but my guess is you're using o."Object Text" "" to cast it as a string. Is that right?
If so, then that is stripping all the rich text (including your borders) before you do anything to it. Try using string objText = richTextWithOle o."Object Text", or string objText = richText o."Object Text", and then try removing the unnecessary parameter to your function string objText, as a reference to this already comes along with Object o
I'm assuming based on how your table looks that it is a RichText table, in which case I believe your code will still work, it's just that I suspect you're starting with a string stripped of richText and adding richtext to it. Sometimes Word OLE objects with tables can look like that too, in which case you'd have to use COM to manipulate the OLE.
Hope this helps.

strtoul() Function- Swift

I'm trying to create a swift iOS program that converts a number into dec, bin, and hex numbers. I've come across the strtoul function, but don't quite understand how to use it, would someone be able to explain it? Thanks!
The method strtoul is pretty simple to use. You will need also to use String(radix:()) to convert it to the other direction. You can create an extension to convert from hexaToDecimal or from binaryToDecimal as follow:
Usage String(radix:())
extension Int {
var toBinary: String {
return String(self, radix: 2)
}
var toHexa: String {
return String(self, radix: 16)
}
}
Usage strtoul()
extension String {
var hexaToDecimal: Int {
return Int(strtoul(self, nil, 16))
}
var hexaToBinary: String {
return hexaToDecimal.toBinary
}
var binaryToDecimal: Int {
return Int(strtoul(self, nil, 2))
}
var binaryToHexa: String {
return binaryToDecimal.toHexa
}
}
Testing
let myBinFromInt = 255.toBinary // "11111111"
let myhexaFromInt = 255.toHexa // "ff"
let myIntFromHexa = "ff".hexaToDecimal // 255
let myBinFromHexa = "ff".hexaToBinary // "11111111"
let myIntFromBin = "11111111".binaryToDecimal // 255
let myHexaFromBin = "11111111".binaryToHexa // "ff"
The strtoul() function converts the string in str to an unsigned long
value. The conversion is done according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.
Really it sounds like you want to use NSString
From what it sounds like, you want to convert an unsigned integer to decimal, hex and binary.
For example, if you had an integer n:
var st = NSString(format:"%2X", n)
would convert the integer to hexadecimal and store it in the variable st.
//NSString(format:"%2X", 10) would give you 'A' as 10 is A in hex
//NSString(format:"%2X", 17) would give you 11 as 17 is 11 in hex
Binary:
var st = NSString(format:"%u", n)
Decimal (2 decimal places)
var st = NSString(format:"%.02f", n)

Resources