画布错误的地方绘制文字[Android]

时间:2015-12-31 21:29:17

标签: android canvas

我有一个应用程序,我使用用户指定的位置在位图上绘制文本。当我要求画布使用x,y坐标绘制文本时,文本会在错误的位置绘制。

Where I position text                    Where it draws after I save

enter image description here enter image description here

保存图片的代码

private void drawText(Bitmap bitmap, TextView mText) {
    try {
        Resources resources = getResources();
        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);             
        paint.setColor(Color.WHITE);               
        paint.setTextSize(text.getTextSize());
        Rect bounds = new Rect();
        paint.getTextBounds(mText.getText().toString(), 0, mText.length(), bounds);

        canvas.drawText(mText.getText().toString(), text.getX() , text.getY(), paint);

        ImageView im = (ImageView) findViewById(R.id.imageView);
        im.setImageBitmap(bitmap);
        saveBitmap(bitmap);

    } catch (Exception e) {
       // TODO: handle exception
    }
}

拖动textview的代码

textView.setOnTouchListener(new View.OnTouchListener() {
    int initialX = 0;
    int initialY = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                initialX = (int) event.getX();
                initialY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int currentX = (int) event.getX();
                int currentY = (int) event.getY();
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) textView.getLayoutParams();

                int left = lp.leftMargin + (currentX - initialX);
                int top = lp.topMargin + (currentY - initialY);
                int right = lp.rightMargin - (currentX - initialX);
                int bottom = lp.bottomMargin - (currentY - initialY);

                lp.rightMargin = right;
                lp.leftMargin = left;
                lp.bottomMargin = bottom;
                lp.topMargin = top;

                textView.setLayoutParams(lp);
                break;
            default:
                break;
        }
        return true;
    }
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        drawText(getBitmap(), textView);
    }
});

0 个答案:

没有答案