3

I am trying to make a a color wheel with pie shaped pieces, wherein each piece of the pie is a button. Here is the code for two of the slices. Currently, the second slice is covering up the first slice with a white background. Is my goal possible?

    ShapeDrawable slice1 = new ShapeDrawable(new ArcShape(0, 30));
    slice1.setIntrinsicHeight(100);     
    slice1.setIntrinsicWidth(100);     
    slice1.getPaint().setColor(Color.MAGENTA);
    View slice1View = (View) findViewById(R.id.slice1);
    slice1View.setBackgroundDrawable(slice1);
    slice1View.setOnClickListener(magentaButtonListener);

    ShapeDrawable slice2 = new ShapeDrawable(new ArcShape(30, 60));
    slice2.setIntrinsicHeight(100);
    slice2.setIntrinsicWidth(100);
    slice2.getPaint().setColor(Color.BLUE);
    View slice2View = (View) findViewById(R.id.slice2);
    slice1View.setBackgroundDrawable(slice2);
    slice1View.setOnClickListener(blueButtonListener);

the layout code is:

    <FrameLayout
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:id="@+id/pie" >


    <View
    android:id="@+id/slice1" 
    android:layout_width="40dp"
    android:layout_height="40dp"/>
    <View
    android:id="@+id/slice2" 
    android:layout_width="40dp"
    android:layout_height="40dp"/>

    </FrameLayout>

Edit! The solution: I set my x and y coordinates to half of the diameter of my circle. Then: I used the getAngle method to calculate the angle, which will decide what color was clicked.

//from StackOverflow post by Dave Discoid, at http://stackoverflow.com/questions/2676719/calculating-the-angle-between-the-line-defined-by-two-points

    public double getAngle(float x, float y )
    {
        double dx = x - DIAMETER/2;
        // Minus to correct for coord re-mapping
        double dy = -(y - DIAMETER/2);

        double inRads = Math.atan2(dy,dx);

        // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
        if (inRads < 0)
            inRads = Math.abs(inRads);
        else
            inRads = 2*Math.PI - inRads;

        return Math.toDegrees(inRads);
    }
tuna
  • 105
  • 2
  • 10
  • can you post your xml layout? – amarunowski Feb 14 '13 at 03:22
  • Just FYI, if I was doing this, my go-to approach would be to have a single custom view with a customized paint/draw method and a custom onClick/onTouch which calculated the angle between x-axis and wherever the user touched – amarunowski Feb 14 '13 at 03:26
  • I added the layout code. Your approach sounds feasible. Can you tell me more about how I would know that angle in the onClick method? I thought onClick just got the coordinates of the click – tuna Feb 14 '13 at 04:30
  • The code you posted is exactly what I was thinking. It's cool, because you can have an arbitrary number of colors :) – amarunowski Feb 14 '13 at 14:23

0 Answers0