• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps working with DrawLine in OnDraw

Is it possible inside ondraw to have a single point of origin for 100 lines ? The length of each line will be user defined from a different activity via intent. The angle of each line is 360/100. essentially i need to build a ray ( angl*lenght(var) for each of my 100 lines. I am having a difficult time inside the android reference locating a method to accomplish this. Anyone have any advice?
 
Sounds like you need a little math to get the job done, but it's a little unclear as to what you want to do. It sounds like you want 100 lines with the same length, radiating from a central point, and all evenly spaced (i.e. the angle between any two adjacent lines is equal to the angle between any other two adjacent lines).

I don't know what you want the point of origin to be, so I'm going to do this using the center of the View. This would all be within onDraw():

Code:
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(1);
final int viewWidth = getWidth();
final int viewHeight = getHeight();
final float centerX = (float)viewWidth/2f;
final float centerY = (float)viewHeight/2f;
// going to use radius (as float) as a class variable for the View, so that it can be set by the user from some other method

for(int i = 0; i < 100; i++) {
    double angle = i*(360.0/100.0)*(Math.PI/180.0); //convert the angle to radians
    canvas.drawLine(centerX, centerY, centerX + radius*(float)Math.cos(angle), centerY + radius*(float)Math.sin(angle), paint);
}
As we run through the for loop, the angle increments (0, 3.6, 7.2, .. ,356.4 [in degrees]), which changes the end point of each line. If you don't want the center point to be the actual center of the View, just change centerX and centerY to something else. Note that it is not good practice to be declaring doubles in a for loop like that, and the calculation should have been done inside the arguments of drawLine(). I just did it that way to illustrate what's going on a little better. Hope this helps (and has no typos).
 
Back
Top Bottom