2012-05-15 3 views
25

캔버스를 사용하여 배경 및 일부 텍스트가있는 Drawable을 만듭니다. 드로어 블은 EditText 내에서 복합 드로잉 가능으로 사용됩니다.안드로이드 캔버스 drawText 텍스트의 y- 위치

텍스트가 캔버스에 drawText()를 통해 그려지지만 일부 경우 그려지는 텍스트의 y 위치에 문제가 있습니다. 이 경우 일부 문자의 일부가 잘립니다 (이미지 링크 참조). 측위 문제없이

문자 : 위치 문제에

http://i50.tinypic.com/zkpu1l.jpg

문자 텍스트에는 'G', 'J', 'Q', 등 :

http://i45.tinypic.com/vrqxja.jpg

포함

아래 코드에서 문제를 재현 할 수 있습니다.

전문가는 y 위치에 대한 적절한 오프셋을 결정하는 방법을 알고 있습니까?

public void writeTestBitmap(String text, String fileName) { 
    // font size 
    float fontSize = new EditText(this.getContext()).getTextSize(); 
    fontSize+=fontSize*0.2f; 
    // paint to write text with 
    Paint paint = new Paint(); 
    paint.setStyle(Style.FILL); 
    paint.setColor(Color.DKGRAY); 
    paint.setAntiAlias(true); 
    paint.setTypeface(Typeface.SERIF); 
    paint.setTextSize((int)fontSize); 
    // min. rect of text 
    Rect textBounds = new Rect(); 
    paint.getTextBounds(text, 0, text.length(), textBounds); 
    // create bitmap for text 
    Bitmap bm = Bitmap.createBitmap(textBounds.width(), textBounds.height(), Bitmap.Config.ARGB_8888); 
    // canvas 
    Canvas canvas = new Canvas(bm); 
    canvas.drawARGB(255, 0, 255, 0);// for visualization 
    // y = ? 
    canvas.drawText(text, 0, textBounds.height(), paint); 

    try { 
     FileOutputStream out = new FileOutputStream(fileName); 
     bm.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

답변

25

내가 그것을 그 내림차순 문자의 경우 그 textBounds.bottom = 0을 가정하는 것은 아마도 실수라고 생각, 그 문자의 하단 부분은 아마 아래 0 (textBounds.bottom을 의미> 0). 당신의 textBounds이 +5에서 -5 경우

canvas.drawText(text, 0, textBounds.top, paint); //instead of textBounds.height()

, 당신은, Y = 높이 (10)에서 텍스트를 그릴 다음은 텍스트의 위쪽 절반을 볼 수 있습니다 : 당신은 아마 뭔가를 원하는 .

canvas.drawText(text, -textBounds.left, -textBounds.top, paint); 

그리고 당신은 두 개의 좌표 변위의 원하는 금액을 합산하여 텍스트 주위에 이동할 수 있습니다 :

+13

올바른 방향으로 나를 가리켜 주셔서 감사합니다. canvas.drawText (text, 0, textBounds.height() - textBounds.bottom, paint); 해결책이었다. – darksaga

10

나는 당신이 왼쪽 상단 모서리 근처에 텍스트를 그릴하려는 경우이 작업을 수행해야한다고 생각

canvas.drawText(text, -textBounds.left + yourX, -textBounds.top + yourY, paint); 

이 (적어도 나를 위해) 작동하는 이유는 DrawText에가() 이벤트 X = 0, Y = 0에서 텍스트를 그릴 것 인 getTextBounds는()를 알 수 있다는 것입니다. 따라서 Android에서 텍스트가 처리되는 방식으로 도입 된 변위 (textBounds.left 및 textBounds.top)를 빼서이 동작을 조정해야합니다.

this answer이 주제에 대해 자세히 설명합니다.