YLS
YLS

Reputation: 1575

how to convert rgb code to hex and set as background color for textview or button in android programatically

Here is my code where i am getting the rgb color code in onTouchListener. In ontouch i get the event x and y position for getting the exact pixel value of the image.

@Override
public boolean onTouch(View v, MotionEvent event) {

    Matrix inverse = new Matrix();
    picked_imageView.getImageMatrix().invert(inverse);
    float[] touchPoint = new float[] {event.getX(), event.getY()};
    inverse.mapPoints(touchPoint);
    int x = Integer.valueOf((int)touchPoint[0]);
    int y = Integer.valueOf((int)touchPoint[1]);

    //int pixel = bitmap.getPixel(x, y);

    int pixel=((BitmapDrawable)picked_imageView.getDrawable()).getBitmap().getPixel(x,y);

    //then do what you want with the pixel data, e.g
    int redValue = Color.red(pixel);
    int blueValue = Color.blue(pixel);
    int greenValue = Color.green(pixel);
    return false;
}

Upvotes: 2

Views: 219

Answers (2)

Blackbelt
Blackbelt

Reputation: 157467

For the sake to showing the value I would suggest you to use Integer.toHexString(int) which returns a String

  String toShow = Integer.toHexString(color)

Upvotes: 1

bonnyz
bonnyz

Reputation: 13558

To get the hex color from the int color (currently your pixel var):

String hexColor = String.format("#%06X", (0xFFFFFF & pixel));

To apply your hex color to a View

view.setBackgroundColor(Color.parseColor(hexColor));

Upvotes: 1

Related Questions