我正在使用Dave Morrissey的子采样比例图像视图来显示高分辨率的地图图像。我想在地图上的预定义坐标处添加位置标记,这样即使在图像被缩放或平移时,标记也会保持在指定的坐标处。我怎么能这样做?
答案 0 :(得分:2)
扩展SubsamplingScaleImageView并覆盖其onDraw()方法
public class MapView extends SubsamplingScaleImageView {
private PointF sPin;
ArrayList<MapPin> mapPins;
ArrayList<DrawnPin> drawnPins;
Context context;
String tag = getClass().getSimpleName();
public MapView(Context context) {
this(context, null);
this.context = context;
}
public MapView(Context context, AttributeSet attr) {
super(context, attr);
this.context = context;
initialise();
}
public void setPins(ArrayList<MapPin> mapPins)
{
this.mapPins = mapPins;
initialise();
invalidate();
}
public PointF getPin() {
return sPin;
}
private void initialise() {
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Don't draw pin before image is ready so it doesn't move around during setup.
if (!isReady()) {
return;
}
drawnPins = new ArrayList<>();
Paint paint = new Paint();
paint.setAntiAlias(true);
float density = getResources().getDisplayMetrics().densityDpi;
for(int i=0;i<mapPins.size();i++)
{
MapPin mPin = mapPins.get(i);
Bitmap bmpPin = Utils.getBitmapFromAsset(context, mPin.getPinImgSrc());
float w = (density/420f) * bmpPin.getWidth();
float h = (density/420f) * bmpPin.getHeight();
bmpPin = Bitmap.createScaledBitmap(bmpPin, (int)w, (int)h, true);
PointF vPin = sourceToViewCoord(mPin.getPoint());
//in my case value of point are at center point of pin image, so we need to adjust it here
float vX = vPin.x - (bmpPin.getWidth()/2);
float vY = vPin.y - (bmpPin.getHeight()/2);
canvas.drawBitmap(bmpPin, vX, vY, paint);
//add added pin to an Array list to get touched pin
DrawnPin dPin = new DrawnPin();
dPin.setStartX(mPin.getX()-w/2);
dPin.setEndX(mPin.getX()+w/2);
dPin.setStartY(mPin.getY()-h/2);
dPin.setEndY(mPin.getY()+h/2);
dPin.setId(mPin.getId());
drawnPins.add(dPin);
}
}
public int getPinIdByPoint(PointF point)
{
for(int i=drawnPins.size()-1;i>=0;i--)
{
DrawnPin dPin = drawnPins.get(i);
if(point.x >= dPin.getStartX() && point.x<=dPin.getEndX())
{
if(point.y >= dPin.getStartY() && point.y<=dPin.getEndY())
{
return dPin.getId();
}
}
}
return -1; //negative no means no pin selected
}
class DrawnPin
{
float startX,startY,endX,endY;
int id;
public DrawnPin(float startX, float startY, float endX, float endY, int id)
{
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
this.id = id;
}
public DrawnPin()
{
//empty
}
public float getStartX()
{
return startX;
}
public void setStartX(float startX)
{
this.startX = startX;
}
public float getStartY()
{
return startY;
}
public void setStartY(float startY)
{
this.startY = startY;
}
public float getEndX()
{
return endX;
}
public void setEndX(float endX)
{
this.endX = endX;
}
public float getEndY()
{
return endY;
}
public void setEndY(float endY)
{
this.endY = endY;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}