如何将以编程方式生成的位图放置在视图中?
How do I place a programatically generated bitmap in a View?
我像这样以编程方式生成了一个圆形位图:
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);
leftMargin 应该是 dotX - imageWidth/2 topMargin 应该是 dotY - imageHeight/2
试试看
我像这样以编程方式生成了一个圆形位图:
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);
leftMargin 应该是 dotX - imageWidth/2 topMargin 应该是 dotY - imageHeight/2
试试看