Android:可点击的饼图

Nik*_*shi -1 android pie-chart

我的App需要一个饼图来显示不同部分的一些数据.饼图已准备就绪,它也可以正常工作,但是当我触及饼图中的特定部分时,我需要一个可点击的事件.请让我知道代码提前谢谢.这是我的android代码

  public class PieActivity extends Activity 
{
/** Called when the activity is first created. */
float values[]={300,700,100,500};

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout linear=(LinearLayout) findViewById(R.id.linear);
    values=calculateData(values);
    linear.addView(new MyGraphview(this,values));

}
private float[] calculateData(float[] data)
{
    // TODO Auto-generated method stub
    float total=0;
    for(int i=0;i<data.length;i++)
    {
        total+=data[i];
    }
    for(int i=0;i<data.length;i++)
    {
    data[i]=360*(data[i]/total);            
    }
    return data;

}
public class MyGraphview extends View
{
    private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
    private float[] value_degree;
    private int[] COLORS={Color.BLUE,Color.GREEN,Color.GRAY,Color.CYAN,Color.RED};
    RectF rectf = new RectF (10, 10, 200, 200);
    int temp=0;
    public MyGraphview(Context context, float[] values) {

        super(context);
        value_degree=new float[values.length];
     //   System.out.println("values"+value_degree);
        for(int i=0;i<values.length;i++)
        {
            value_degree[i]=values[i];
            System.out.println("degree"+value_degree[i]);
        }
    }
    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);

        for (int i = 0; i < value_degree.length; i++) {//values2.length; i++) {
            if (i == 0) {
                paint.setColor(COLORS[i]);
                canvas.drawArc(rectf, 0, value_degree[i], true, paint);
            } 
            else
            {
                    temp += (int) value_degree[i - 1];
                    paint.setColor(COLORS[i]);
                    canvas.drawArc(rectf, temp, value_degree[i], true, paint);
            }
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

Pal*_*asz 5

你可以试试这个:

  • 在MyGraphView中覆盖onTouchEvent并检查操作.通常对于ACTION_DOWN,您应该返回true,并在ACTION_UP处理单击.

  • 处理单击时,从图表的中心提取相对事件坐标,如

    float relX = event.getX() - (rectf.right - rectf.left) * 0.5f;
    float relY = event.getY() - (rectf.bottom - rectf.top) * 0.5f;
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后你需要找到角度:

    float angleInRad = (float)Math.atan2(relY, relX);
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在你已经得到了角度,但是以弧度和-PI..PI为范围.所以:

    int degree = (int)((angleInRad + Math.PI) * 180 / Math.PI);
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在只需查找哪个区间(来自value_degree)包含此值.

另请注意,由于坐标系是颠倒的,您可能需要使用-relY而不是relY.只需尝试并根据需要进行更改.