沿着无限的动态路径移动位图或imageView

时间:2019-02-05 14:49:39

标签: java android canvas

我有一些来自服务器(x,y)坐标的数据。我想使一个位图(最好是ImageView)跟随我在视图中使用该坐标创建的路径移动。这是我试图实现的目标: 这是获取数据的回调:

private class Coordinate implements ObjectPositionListener {
    public  void onObjectPositions(List<DataSmlPositionProtocol.ObjectPositionScreen> objects){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (dataText != null){
        final String this_text = "x=" + objects.get(0).x + " y = " + objects.get(0).y;
        dataText.setText(this_text); // dataText is a textView
                }
            currentPosition = objects;
            }
        });
    }
}

这是我的onDraw方法:

@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (currentPosition != null) {
        square();
        if (bmp != null)
            canvas.drawBitmap(bmp, 0, 0, paints);

        Log.d(TAG, "X: "+ currentPosition.get(0).x + " and y: "+ currentPosition.get(0).y);

        aPoints.add(new PointF(currentPosition.get(0).x, currentPosition.get(0).y));

        PointF point = aPoints.get(0);
        ptCurve.moveTo(point.x, point.y);
        for (int i = 0; i < aPoints.size() - 1; i++) {
            point = aPoints.get(i);
            PointF next = aPoints.get(i + 1);
            ptCurve.quadTo(point.x, point.y, (next.x + point.x) / 2, (point.y + next.y) / 2);
        }
        if(pm == null) {
            pm = new PathMeasure(ptCurve, false);
        }
        fSegmentLen = pm.getLength() / iMaxAnimationStep;



        if (iCurStep <= iMaxAnimationStep) {
            pm.getMatrix(fSegmentLen * iCurStep,
                    mxTransform,
                    PathMeasure.POSITION_MATRIX_FLAG + PathMeasure.TANGENT_MATRIX_FLAG);
            mxTransform.preTranslate(-bmp.getWidth(), -bmp.getHeight());

            canvas.drawBitmap(bmp, mxTransform, null);

            iCurStep += 1; //advance to the next step

            if(iCurStep == iMaxAnimationStep) {
                iCurStep = 0;
            }

            invalidate();
        } else {
            iCurStep = 0;
        }
    }


}

我可以在Log中看到onDraw方法中的X,Y正在更改。我创建了一些位图:

private void setupDrawing() {
    path = new Path();
    paints = new Paint();
    paints.setColor(Color.GREEN);
}

public void square() {
    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    bmp = Bitmap.createBitmap(200, 200, conf);
    Canvas canvas = new Canvas(bmp);
    path.moveTo(0, 0);
    path.lineTo(this.getWidth() - 50, 0);
    path.lineTo(this.getWidth() - 50, this.getHeight() - 50);
    path.lineTo(0, this.getHeight() - 50);
    path.lineTo(0, 0);
    canvas.drawPath(path, paints);
}

我在视图上获得了位图,但是没有移动。我想也许是因为X,Y是固定的。路径不固定,因为x,y一直在变化。请问有什么解决办法吗?是否还有除bitmap和onDraw之外的其他解决方案?

0 个答案:

没有答案