Circle drawn on canvas doesn't match the scree

2019-05-02 16:02发布

问题:

I want to draw circle in center of screen, but I'm getting something like this:

I'm using this code to draw this circle.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Display display = getWindowManager().getDefaultDisplay(); 
    int width = display.getWidth();
    int height = display.getHeight();

    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

    Canvas c = new Canvas(bmp);

    RectF rect = new RectF(0,0,width,width);
    drawCircle(rect, c, width, height);
    ImageView img = (ImageView) findViewById(R.id.imageView1);
    img.setImageBitmap(bmp);
    img.setScaleType(ScaleType.FIT_CENTER);


}

private void drawCircle(RectF rect, Canvas c, int width, int height) {
    Paint paint = new Paint();
    paint.setARGB(255, 255 , 10, 21);
    paint.setStrokeWidth(10);
    paint.setAntiAlias(true);
    paint.setStrokeCap(Paint.Cap.BUTT);
    paint.setStyle(Paint.Style.STROKE);
    int radius;
    if(width < height)
        radius = width/2;
    else 
        radius = height/2;
    c.drawCircle(width/2, height/2, radius, paint);
}

I don't understand why it's cut at sides even though I use size of screen to draw it, so it should perfectly fit it.

回答1:

You didn't account for the thickness of the line (strokeWidth). You drew a circle assuming it had 0 thickness, so the "actual" circle IS touching the edges of the screen, but since you used a thick paintbrush, some of the paint leaked past the edge.



回答2:

you should decrease the thickness/2.

    private void drawCircle(RectF rect, Canvas c, int width, int height) {
        Paint paint = new Paint();
        paint.setARGB(255, 255 , 10, 21);
        paint.setStrokeWidth(10);
        paint.setAntiAlias(true);
        paint.setStrokeCap(Paint.Cap.BUTT);
        paint.setStyle(Paint.Style.STROKE);
        int radius;
        if(width < height)
            radius = width/2;
        else 
            radius = height/2;

//this is the new line:
        radius-= 5;
        c.drawCircle(width/2, height/2, radius, paint);
    }


回答3:

Account for the StrokeWidth in the radius:

// Substract stroke width.
radius -= paint.getStrokeWidth() / 2;
c.drawCircle(width/2, height/2, radius, paint);