Canvas drawtext positioning

社会主义新天地 提交于 2019-12-10 15:53:39

问题


I am creating a drawing tool, where user add text to image. While making the text draw to bitmap via canvas position is not being set properly.

Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.RED);
        paint.setTypeface(tf);
        paint.setTextAlign(Paint.Align.LEFT);

        paint.setTextSize(30);



int xPos = layoutTextViewContainer.getLeft();
        int yPos = layoutTextViewContainer.getTop();
        canvas.drawText(text, xPos, yPos, paint);

Paint

Rect textRect = new Rect();
        paint.getTextBounds(text, 0, text.length(), textRect);
        textRect.offset(0, -textRect.top);
        Canvas canvas = new Canvas(bm);

layoutTextViewContainer holds the edit text. Screen shot for more clarification. Black text is written and Red text is preview of embed in image


回答1:


Got the solution. the values should be pixel independent convert xPos and yPos as below before passing to drawText

 xPos = (int) (xPos / getResources().getDisplayMetrics().density);
    yPos = (int) (yPos / getResources().getDisplayMetrics().density);



回答2:


Its even better to use Drawing cache and save that to any file location. In this case we dont have to much bother about positioning. Wrap all in one layout and get the

 view.getDrawingCache()


来源:https://stackoverflow.com/questions/25176321/canvas-drawtext-positioning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!