canvas.drawCircle sometimes working, sometimes not
I bought the book Programming Android, and it's a little confusing and disappointing on how they have different code in their Github (https://github.com/bmeike/ProgrammingAndroid2Examples/tree/master/AndroidUIDemo) and their book. I'm stuck in an example that teaches how to draw a circle in a random point, with the color that is assigned to the button, like, when I click the RED button, it should draw a red circle in a view.
I did some extra code and somehow I managed to get it working. Here is my onDraw method:
@Override
protected void onDraw(Canvas canvas)
{
paint.setStyle(Style.STROKE);
paint.setColor(hasFocus() ? Color.BLUE : Color.GRAY);
canvas.drawRect(0, 0, getWidth() - 1, getHeight() - 1, paint);
if (this.points == null) return;
paint.setStyle(Style.FILL);
for (Point p : points.getAllPoints())
{
paint.setColor(p.getColor());
canvas.drawCircle(p.getX(), p.getY(),
p.getDiameter(), paint);
}
}
Sometimes it works, sometimes not, BUT when it works, it draws a thin, large oval shape.
p.getDiameter()
is ALWAYS 6. Even if I put it to a fixed 6, the effect is the same.
Also, there is some strange thing happening: If I replace p.getY()
and p.getX()
by 50
, it will never draw anything on the screen. 50 should not be out of the screen bounds.
Unfortunately I can't post a screenshot, my device is not rooted.
Here is some extra relevant code.
Setting the pointView size (the place where I draw points):
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
pointView.setLayoutParams(new android.widget.LinearLayout.LayoutParams(root.getWidth(), root.getHeight()/2));
}
Add an OnCLickListener to the button, so when I click it, it should draw a circle.
button1.setOnClickListener(new OnClickListener() //I'll not put the Red button here, for the sake of brevity.
{
@Override
public void onClick(View arg0)
{
makeDot(pointModel, pointView, Color.GREEN);
}
});
And the makeDot method:
private final Random rnd = new Random();
void makeDot(Points points, PointView pointView, int color)
{
points.addPoint(
rnd.nextFloat()*pointView.getWidth(),
rnd.nextFloat()*pointView.getHeight(),
color, POINT_DIAMETER /*always 6*/);
}
(I think POINT_DIAMETER should be POINT_RADIUS but it's OK for now.)
So, how can I get it to draw a round circle in a random position in the screen?
Read more
stackoverflow.comm
No comments:
Post a Comment