画布上绘制的圆圈与屏幕不匹配

时间:2013-01-08 14:50:24

标签: android graphics canvas

我想在屏幕中心画圆圈,但我得到的是这样的东西:

enter image description here

我正在使用此代码绘制此圈子。

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);
}

我不明白为什么它会在侧面切割,即使我使用屏幕尺寸来绘制它,所以它应该完全适合它。

3 个答案:

答案 0 :(得分:7)

您没有考虑线条的粗细(strokeWidth)。假设它有0厚度,你画了一个圆,所以&#34;实际&#34;圆形触摸屏幕的边缘,但由于你使用了厚厚的画笔,一些油漆漏过了边缘。

答案 1 :(得分:2)

你应该减少厚度/ 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);
    }

答案 2 :(得分:1)

考虑半径中的StrokeWidth

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