【发布时间】:2017-06-01 09:39:19
【问题描述】:
我想在view 上画一个polyline。我不想在MapView 上画它,因为我只想要没有任何背景的polyline。
我有polyline 坐标,也有它的边界(东北和西南坐标)。
这个想法是创建一个自定义view 并在那里绘制路径。我相信我遇到的问题是规模。我可以将LatLng 坐标转换为x 和y 坐标,但是view 上显示的折线太小。 view 设置为 64dp 的宽度和高度。
这是我正在做的事情:
public PolylineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
polylineSize = (int) context.getResources().getDimension(R.dimen.polyline_size);
setupAttributes(attrs);
}
private void setupAttributes(AttributeSet attrs) {
// Obtain a typed array of attributes
TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.PolylineView, 0, 0);
// Extract custom attributes into member variables
try {
polylineColor = a.getColor(R.styleable.PolylineView_polylineColor, Color.BLACK);
} finally {
// TypedArray objects are shared and must be recycled.
a.recycle();
}
polyline = new Paint(Paint.ANTI_ALIAS_FLAG);
polyline.setAntiAlias(true);
polyline.setStyle(Paint.Style.STROKE);
polyline.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
polyline.setStrokeCap(Paint.Cap.ROUND);
polyline.setColor(polylineColor);
path = new Path();
smp = new SphericalMercatorProjection(polylineSize);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
point = smp.toPoint(polylineCoordinates.get(0));
path.moveTo((float) (point.x * scale), (float) (point.y * scale));
for (int i = 1; i < polylineCoordinates.size(); i++) {
point = smp.toPoint(polylineCoordinates.get(i));
path.lineTo((float) (point.x * scale), (float) (point.y * scale));
}
canvas.drawPath(path, polyline);
}
public void setPolyline(List<LatLng> polylineCoordinates, RealmLatLngBounds polylineBounds) {
this.polylineBounds = polylineBounds;
this.polylineCoordinates = polylineCoordinates;
//Find the scale
Point northeast = smp.toPoint(polylineBounds.getNortheast());
Point southwest = smp.toPoint(polylineBounds.getSouthwest());
scale = polylineSize / Math.max(Math.max(northeast.x, southwest.x), Math.max(northeast.y, southwest.y));
invalidate();
requestLayout();
}
之后我可以转换polyline 坐标以便使用view 的完整大小吗?
编辑:
【问题讨论】:
-
@pskink 我这样做了
scale = Math.max(northeast.x / southwest.x, southwest.y / northeast.y);但仍然没有成功 -
没有。还是同样的问题。看我附上的图片。可能与精度有关。
-
@pskink 谢谢。这非常有用。我仍然遇到问题,因为项目在 recyclerview 中,但会找到答案。
-
它是否在recyclerview中并不重要
-
我设法解决了它。非常感谢。你不想把你的答案写出来让我接受吗?
标签: android coordinates coordinate-transformation