drawText在错误的位置

时间:2017-03-14 10:11:52

标签: java android canvas

使用onDraw()方法创建一个蓝图,您可以动态添加标记。添加标记工作正常,但我还想在标记上放置一个带有数字的文本。该号码是QR码。当我放置第一个标记时,文本位置总是错误的(见图)。以下放置的标记确实具有正确的位置。有人知道这是怎么回事吗?

Example blueprint text

    @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 = mPin.getBitmap();

        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);

        String qrid = String.valueOf(mPin.getQrid());
        qrid = qrid.substring(qrid.length() - 3);


        //add added pin to an Array list to get touched pin
        DrawPin dPin = new DrawPin();
        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);

        float GESTURE_THRESHOLD_DIP = 16.0f;

        // Convert the dips to pixels
        final float scale = getContext().getResources().getDisplayMetrics().density;
        int mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f);

        Rect bounds = new Rect();
        paint.getTextBounds(qrid, 0, qrid.length(), bounds);
        System.out.println("textHeight: " + bounds.height() + ", textWidth: "  + bounds.width());

        float bWidth = (density / 420f) * bounds.width();
        float bHeight = (density / 420f) * bounds.height();
        Log.d(TAG, "x: " + vPin.x + ", y: " + vPin.y);
        System.out.println("bHeight: " + bHeight + ", bWidth: "  + bWidth);

        float tX = vPin.x - (bWidth / 2);
        float tY = vPin.y + (bHeight / 2);
        //float tY = vPin.y - (bHeight / 2);

        paint.setTextSize(mGestureThreshold);
        paint.setColor(Color.BLACK);
        canvas.drawBitmap(bmpPin, vX, vY, paint);
        canvas.drawText(qrid, tX, tY, paint);


    }
}

1 个答案:

答案 0 :(得分:0)

首先通过创建一个不可见的“虚拟”标记来解决此问题,以便以下标记将文本放在正确的位置。

相关问题