LoginSignup
5
4

More than 5 years have passed since last update.

Android開発、RGB、16進数、リソースファイルからの色の実装についてをまとめてみた

Last updated at Posted at 2018-05-22

Colorについて

Android開発でUIデザインをいじっていたときにハマってしまったので整理してみました。
16進数から色を指定したり、リソースファイルから指定できたりします。
iOSではリソースファイルみたいなものはないので概念を理解するのに時間がかかってしまった。
僕にとって厄介だったのはResourceファイルという概念でした。

色リソースからの設定(一番ハマるのでトップにしました)

Res(Resource)フォルダのcolor.xmlにキーを設定していれば使えるやり方。
実務でよく見られる方法。

Resource.java
Resources res = getResources();
int chocolate_color = res.getColor(R.color.chocolate);

TextView text = new TextView(this);
text.setBackgroundColor(chocolate_color);

color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="chocolate">#d2691e</color>
</resources>

#RGB形式 でのColorの設定

Rgb.java
TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("#FF00C0"));

// "#FF_00_C0"
// RGB

parseColorのメソッドは
public static int parseColor(String colorString)
ということで引数がString型 、返り値はint型である。
Colorはどうやら、 int color というものらしい。

ARGB形式でのColorの設定

Argb.java
TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("#FF0F00C0"));

// "#FF_0F_00_C0"
// ARGB

キーワード形式でのColorの設定

使えるキーワードは下のキーワード

red
blue
green
black
white
gray
cyan
magenta
yellow
lightgraydarkgray

Word.java

TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("magenta"));

Colorクラスからのデフォルト定数?

  • Color.BLACK:黒
  • Color.BLUE:青
  • Color.CYAN:シアン
  • Color.DKGRAY:ダークグレイ
  • Color.GRAY:グレイ
  • Color.GREEN:緑
  • Color.LTGRAY:ライトグレイ
  • Color.MAGENTA:マゼンタ
  • Color.RED:赤
  • Color.TRANSPARENT:透明
  • Color.WHITE:白
  • Color.YELLOW:黄色

16進数からintに変換してcolorを設定する方法(うる覚え)

Intcolor.java
String white = "#ffffff";
int whiteInt = Color.parseColor(white);

TextView text = new TextView(this);
text.setBackgroundColor(whiteInt);

16進数文字列とバイト列を相互変換する方法

hex.java
public static String bin2hex(byte[] data) {
    StringBuffer sb = new StringBuffer();
    for (byte b : data) {
        String s = Integer.toHexString(0xff & b);
        if (s.length() == 1) {
            sb.append("0");
        }
        sb.append(s);
    }
    return sb.toString();
}

public static byte[] hex2bin(String hex) {
    byte[] bytes = new byte[hex.length() / 2];
    for (int index = 0; index < bytes.length; index++) {
        bytes[index] = (byte) Integer.parseInt(hex.substring(index * 2, (index + 1) * 2), 16);
    }
    return bytes;
}

これだけ押さえておけばこのページを見てすぐに色変換ができるようになるかなと思います。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4