ImageView 默认是透明的。
您的指示图像资源应具有透明背景(例如透明 .PNG 图像)。
只需将 ImageView 的 imageResource 或 backgroundResource 设置为 PNG 文件即可。
因此,您创建 ImageView 的代码将如下所示:
ImageView myImageView = new ImageView(context);
myImageView.setBackgroundColor(0x0); // not needed - it's the default
myImageView.setImageResource(R.drawable.indicator_icon);
但同样,这是默认设置,您仍然必须确保图像的背景是透明的,否则 ImageView 的背景将无关紧要。
更新:在@eros 更新问题后,这里有一个更新的答案:
我能想到有两个选项可以实现将一个图像视图定位在另一个图像视图之上:
- 使用 LayoutParams 并将边距设置为指示器图像视图的位置
- 在地图 bmp 的画布上绘制指示器图像视图
我个人更喜欢第一个选项,因为未来的更改不会迫使您重新绘制指标。
这是一个演示选项 (1) 的课程:
public class MyMapView extends RelativeLayout {
private ImageView mBackImageView;
private ImageView mIndicatorImageView;
public MyMapView(Context context) {
super(context);
mBackImageView = new ImageView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mBackImageView.setImageResource(R.drawable.image1);
mBackImageView.setScaleType(ImageView.ScaleType.FIT_XY);
addView(mBackImageView, params);
mIndicatorImageView = new ImageView(context);
RelativeLayout.LayoutParams indParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mIndicatorImageView.setImageResource(R.drawable.image2);
addView(mIndicatorImageView, indParams);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
centerIndicatorPosition();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerIndicatorPosition();
}
// @eros: this's the part you want. this method just centers the indicator view
// but if you have the relative position like you say, use it for the margins
private void centerIndicatorPosition() {
int xPos = (getMeasuredWidth() - mIndicatorImageView.getMeasuredWidth()) / 2;
int yPos = (getMeasuredHeight() - mIndicatorImageView.getMeasuredHeight()) / 2;
((RelativeLayout.LayoutParams)mIndicatorImageView.getLayoutParams())
.setMargins(xPos, yPos, 0, 0);
}
}