如何在视图中放置以编程方式生成的位图?

时间:2017-02-07 21:28:20

标签: java android view bitmap relativelayout

我以编程方式生成了一个圆形位图:

private Bitmap drawDotCircle() {
        int circleSize = 100;
        circleBitmap = Bitmap.createBitmap(
                circleSize,
                circleSize,
                Bitmap.Config.ARGB_8888
        );

        canvas = new Canvas(circleBitmap);
        CanvasRadius = Math.min(canvas.getWidth(), canvas.getHeight() / 2);

        // Create a Paint object used to paint the circle
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);

        canvas.drawCircle(
                canvas.getWidth() / 2,
                canvas.getHeight() / 2,
                CanvasRadius - CanvasPadding,
                paint
        );

        return circleBitmap;
    }

我想把它放在我计算的绝对X和Y上;让我们假设它是屏幕的绝对中心,如下所示:

int dotX =getResources().getDisplayMetrics().widthPixels / 2;
int dotY = getResources().getDisplayMetrics().heightPixels / 2;

如何确保圆圈在视图中居中?我尝试了以下代码,但由于某种原因,圆圈总是偏离中心:

        RelativeLayout.LayoutParams layoutParams =
                new RelativeLayout.LayoutParams(circleDot.getHeight(), circleDot.getHeight());

// Setting position of our ImageView
        layoutParams.leftMargin = dotX;
        layoutParams.topMargin = dotY;

// Finally Adding the imageView to RelativeLayout and its position
        relativeLayout.addView(dotView, layoutParams);

1 个答案:

答案 0 :(得分:0)

leftMargin应为dotX - imageWidth / 2,topMargin应为dotY - imageHeight / 2

试试