JavaScript를 사용하여 문자열을 기반으로 16 진수 색상 만들기
나는 오래된 문자열 (보통 될 것입니다 한 단어)와 그 허용 할 함수 만들려면 어떻게 든 사이의 16 진수 값을 생성 #000000
하고 #FFFFFF
난 HTML 요소의 색상으로 사용할 수 있도록를.
#FFF
덜 복잡한 16 진수 값 (예 :) 일 수도 있습니다. 실제로 '웹 안전'팔레트의 색상이 이상적입니다.
임의의 문자열 에 대한 Compute hex 색상 코드 에서 Javascript로 Java를 이식하면 됩니다.
function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
변환하려면 다음을 수행하십시오.
intToRGB(hashCode(your_string))
다음은 6 자리 색상 코드를 일관되게 반환하는 CD Sanchez의 답변에 대한 수정입니다.
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
용법:
stringToColour("greenish");
// -> #9bc63b
예:
(대체 / 간단한 솔루션은 'rgb (...)'스타일 색상 코드를 반환하는 것을 포함 할 수 있습니다.)
HTML 요소의 색상이 풍부하고 풍부하기를 원했지만 CSS가 이제 hsl () 색상을 지원한다는 사실에 놀랐습니다. 따라서 전체 솔루션은 다음과 같습니다.
N "고유 한"색상을 자동으로 생성하는 방법 도 참조하십시오 . 이와 유사한 더 많은 대안이 필요합니다.
function colorByHashCode(value) {
return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";
}
String.prototype.getHashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (var i = 0; i < this.length; i++) {
hash = this.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
Number.prototype.intToHSL = function() {
var shortened = this % 360;
return "hsl(" + shortened + ",100%,30%)";
};
document.body.innerHTML = [
"javascript",
"is",
"nice",
].map(colorByHashCode).join("<br/>");
span {
font-size: 50px;
font-weight: 800;
}
HSL에서 색조, 채도, 가벼움. 따라서 0-359 사이의 색조는 모든 색상을 얻을 수 있으며 채도는 색상을 얼마나 풍부하게 원하는지, 100 %는 저에게 효과적입니다. 밝기는 깊이를 결정하고, 50 %는 보통, 25 %는 어두운 색, 75 %는 파스텔입니다. 내 색 구성표에 가장 적합하기 때문에 30 %가 있습니다.
임의의 색상을 생성하면 내 취향에 대비가 충분하지 않은 색상이 생성되는 경향이 있습니다. 내가 찾은 가장 쉬운 방법은 매우 다른 색상 목록을 미리 채우는 것입니다. 모든 새 문자열에 대해 목록에서 다음 색상을 지정하십시오.
// Takes any string and converts it into a #RRGGBB color.
var StringToColor = (function(){
var instance = null;
return {
next: function stringToColor(str) {
if(instance === null) {
instance = {};
instance.stringToColorHash = {};
instance.nextVeryDifferntColorIdx = 0;
instance.veryDifferentColors = ["#000000","#00FF00","#0000FF","#FF0000","#01FFFE","#FFA6FE","#FFDB66","#006401","#010067","#95003A","#007DB5","#FF00F6","#FFEEE8","#774D00","#90FB92","#0076FF","#D5FF00","#FF937E","#6A826C","#FF029D","#FE8900","#7A4782","#7E2DD2","#85A900","#FF0056","#A42400","#00AE7E","#683D3B","#BDC6FF","#263400","#BDD393","#00B917","#9E008E","#001544","#C28C9F","#FF74A3","#01D0FF","#004754","#E56FFE","#788231","#0E4CA1","#91D0CB","#BE9970","#968AE8","#BB8800","#43002C","#DEFF74","#00FFC6","#FFE502","#620E00","#008F9C","#98FF52","#7544B1","#B500FF","#00FF78","#FF6E41","#005F39","#6B6882","#5FAD4E","#A75740","#A5FFD2","#FFB167","#009BFF","#E85EBE"];
}
if(!instance.stringToColorHash[str])
instance.stringToColorHash[str] = instance.veryDifferentColors[instance.nextVeryDifferntColorIdx++];
return instance.stringToColorHash[str];
}
}
})();
// Get a new color for each string
StringToColor.next("get first color");
StringToColor.next("get second color");
// Will return the same color as the first time
StringToColor.next("get first color");
이것은 64 색으로 제한되지만 대부분의 인간은 그 이후의 차이점을 실제로 알 수 없습니다. 항상 더 많은 색상을 추가 할 수 있다고 가정합니다.
이 코드는 하드 코딩 된 색상을 사용하지만 최소한 개발 과정에서 프로덕션 환경에서 색상 사이의 대비 정도를 알고 있어야합니다.
이 SO answer 에서 색상 목록이 해제되었으며 색상이 더 많은 다른 목록이 있습니다.
If your inputs are not different enough for a simple hash to use the entire color spectrum, you can use a seeded random number generator instead of a hash function.
I'm using the color coder from Joe Freeman's answer, and David Bau's seeded random number generator.
function stringToColour(str) {
Math.seedrandom(str);
var rand = Math.random() * Math.pow(255,3);
Math.seedrandom(); // don't leave a non-random seed in the generator
for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
return colour;
}
I have opened a pull request to Please.js that allows generating a color from a hash.
You can map the string to a color like so:
const color = Please.make_color({
from_hash: "any string goes here"
});
For example, "any string goes here"
will return as "#47291b"
and "another!"
returns as "#1f0c3d"
Yet another solution for random colors:
function colorize(str) {
for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
return '#' + Array(6 - color.length + 1).join('0') + color;
}
It's a mixed of things that does the job for me. I used JFreeman Hash function (also an answer in this thread) and Asykäri pseudo random function from here and some padding and math from myself.
I doubt the function produces evenly distributed colors, though it looks nice and does that what it should do.
Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.
It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.
Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette
//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {
//TODO: adjust base colour values below based on theme
var baseRed = 128;
var baseGreen = 128;
var baseBlue = 128;
//lazy seeded random hack to get values from 0 - 256
//for seed just take bitwise XOR of first two chars
var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;
//build colour
var red = Math.round((rand_1 + baseRed) / 2);
var green = Math.round((rand_2 + baseGreen) / 2);
var blue = Math.round((rand_3 + baseBlue) / 2);
return { red: red, green: green, blue: blue };
}
GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd
Using the hashCode
as in Cristian Sanchez's answer with hsl
and modern javascript, you can create a color picker with good contrast like this:
function hashCode(str) {
let hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function pickColor(str) {
return `hsl(${hashCode(str) % 360}, 100%, 80%)`;
}
one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
div {
padding: 10px;
}
<div id="one">One</div>
<div id="two">Two</div>
Since it's hsl, you can scale luminance to get the contrast you're looking for.
function hashCode(str) {
let hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function pickColor(str) {
// Note the last value here is now 50% instead of 80%
return `hsl(${hashCode(str) % 360}, 100%, 50%)`;
}
one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
div {
color: white;
padding: 10px;
}
<div id="one">One</div>
<div id="two">Two</div>
Here is another try:
function stringToColor(str){
var hash = 0;
for(var i=0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 3) - hash);
}
var color = Math.abs(hash).toString(16).substring(0, 6);
return "#" + '000000'.substring(0, 6 - color.length) + color;
}
This function does the trick. It's an adaptation of this, fairly longer implementation this repo ..
const color = (str) => {
let rgb = [];
// Changing non-hexadecimal characters to 0
str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
// Padding string with zeroes until it adds up to 3
while (str.length % 3) str += '0';
// Dividing string into 3 equally large arrays
for (i = 0; i < str.length; i += str.length / 3)
rgb.push(str.slice(i, i + str.length / 3));
// Formatting a hex color from the first two letters of each portion
return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
}
I convert this for Java.
Tanks for all.
public static int getColorFromText(String text)
{
if(text == null || text.length() < 1)
return Color.BLACK;
int hash = 0;
for (int i = 0; i < text.length(); i++)
{
hash = text.charAt(i) + ((hash << 5) - hash);
}
int c = (hash & 0x00FFFFFF);
c = c - 16777216;
return c;
}
'programing tip' 카테고리의 다른 글
리사이클 러보기 및 다양한 유형의 행 인플레이션 처리 (0) | 2020.07.09 |
---|---|
CSS를 사용하여 빈 입력 상자 일치 (0) | 2020.07.09 |
IntentService와 서비스의 차이점은 무엇입니까? (0) | 2020.07.09 |
https를 통해 파일을 다운로드하려면 openssl 확장을 활성화해야합니다 (0) | 2020.07.09 |
JVM 인수를 통한 log4j 구성? (0) | 2020.07.09 |