我想在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
的全尺寸?
編輯:
其中之一,我可以看到轉換爲x
和y
時的問題,值是兩個親密的(精度)
@pskink我做了這個'scale = Math.max(northeast.x/southwest.x,southwest.y/northeast.y);'但仍然沒有成功 – Favolas
沒有。仍然是同樣的問題。看到我附上的圖片。可能與精確度有關。 – Favolas
@pskink謝謝。這非常有用。我仍然有問題,因爲物品在回收站內,但會找到答案。 – Favolas