1

I have a custom view which draws a "pie chart". The initial drawing works fine. Now I want to do some kind of hittest so I know which of the pie segments was touched so that I can rotate the canvas and the touched segment to the top. The problem is that I don't know how I get the segment that was touched.

My class so far:

public class BlinkerView extends View {
float start;
int[] data = {1,1,1,1,1,1,1};
int numberOfparts = 7;
private int[] colors = { Color.parseColor("#c62d30"),
                        Color.parseColor("#d67d2e"),
                        Color.parseColor("#f2e742"),
                        Color.parseColor("#a4c136"),
                        Color.parseColor("#c82b85"),
                        Color.parseColor("#f3f3f3"),
                        Color.parseColor("#77beee")};

public BlinkerView(Context context) {
    super(context);

    setFocusable(true);
    this.start = -90 - ((360 / numberOfparts) / 2);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    rootCanvas = canvas;

    canvas.drawColor(Color.WHITE);

    // Color segments
    Paint colorSegment = new Paint();
    colorSegment.setAntiAlias(true);
    colorSegment.setColor(Color.RED);
    colorSegment.setStyle(Paint.Style.STROKE);
    colorSegment.setStrokeWidth(0);
    colorSegment.setStyle(Paint.Style.FILL);
    float[] scaledValues = scale();

    RectF rectF = new RectF(0,0, getWidth(), getWidth());

    colorSegment.setColor(Color.WHITE);

    for(int i = 0; i < numberOfparts; i++){
        colorSegment.setColor(colors[i]);
        colorSegment.setStyle(Paint.Style.FILL);
        colorSegment.setFlags(i);

        canvas.drawArc(rectF, start, scaledValues[i],true, colorSegment);
        start = start + scaledValues[i];
    }
}

private float[] scale() {
    float[] scaledValues = new float[this.data.length];
    float total = getTotal(); //Total all values supplied to the chart

    for (int i = 0; i < this.data.length; i++) {
        scaledValues[i] = (this.data[i] / total) * 360; //Scale each value
    }

    return scaledValues;
}

private float getTotal() {
    float total = 0;
    for (float val : this.data)
        total += val;
    return total;
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // WHICH COLOR SEGMENT WAS HIT?

            break;
    }

    invalidate();
    return true;
}
Patricks
  • 715
  • 2
  • 12
  • 25

0 Answers0