Cannot get Color.HSVToColor to work on Android

theV0ID picture theV0ID · Mar 30, 2013 · Viewed 10.2k times · Source

I've derived a class from View and implemented the onDraw method as follows:

protected void onDraw( Canvas canvas )
{
    Paint p = new Paint();
    p.setColor( Color.HSVToColor( new float[]{ 1.f, 1.f, 1.f } ) );
    p.setStyle( Paint.Style.FILL );
    canvas.drawRect( area, p );
}

I'm expecting to see an however colored rectangle, but the screen stays white, no metter which values I try for hue, value and saturation. The variable area is a RectF. It's fine, because if I put color to Color.RED, it works.

The Android documentation states on Color.HSVToColor:

Convert HSV components to an ARGB color. Alpha set to 0xFF. hsv[0] is Hue [0 .. 360) hsv[1] is Saturation [0...1] hsv[2] is Value [0...1] If hsv values are out of range, they are pinned.

I've tried lots of hue/saturation/value combinations, but the screen always remained blank. Furthermore I've tried the following, with same results:

float[] hsv = new float[ 3 ];
Color.colorToHSV( Color.RED, hsv );

Paint p = new Paint();
p.setColor( Color.HSVToColor( hsv ) );
p.setStyle( Paint.Style.FILL );
canvas.drawRect( area, p );

What am I doing wrong?

Answer

Raghunandan picture Raghunandan · Mar 30, 2013

Your draw should work fine. There must be something missing or something other than the draw that you are not doing right.

mpaint.setColor( Color.HSVToColor( new float[]{ 1f, 1f, 1f } ) );   

The above should set color to red.

I have done similar to what you have done in onDraw() except that i changed the value and it works.

public class FingerPaintActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView mv= new MyView(this);
setContentView(mv);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
class MyView extends View
{
    Context c;      
    private Paint mpaint;

public MyView(Context context) {
    super(context);
    c= context;
    mpaint= new Paint();
    //mpaint.setColor(Color.RED);
    mpaint.setColor( Color.HSVToColor( new float[]{ 0f, 0f, 0.5f } ) );
    mpaint.setStyle(Paint.Style.FILL);
 }

    @Override
    protected void onDraw(Canvas canvas) {
       canvas.drawRect(300, 100, 200, 300, mpaint);

    }
}
}

http://developer.android.com/reference/android/graphics/Color.html#HSVToColor%28int,%20float%5B%5D%29.

enter image description here