2017-03-07 73 views
0

我有一个很长的字符串,我肯定不会放在图像上。所以我结束了计算线条,然后使用CanvasBitmap上逐行写入。问题是只有第一行被写入。我会一直在写这个图像。每行的长度固定为40个字符。请在下面检查代码:在循环中的画布上绘制文本

private Bitmap prepareImageWithText(String text){ 
     Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.text_image); // Load your bitmap here 
     Bitmap aBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); // copy the bitmap because the one from the Resources is immutable. 
     Canvas canvas = new Canvas(aBitmap); 
     Paint paint = new Paint(); 
     paint.setColor(Color.BLACK); 
     paint.setTextSize(75); 

     for(int i=0; i<calculateLines(text); i++) { 
      int beginFrom = i*40; 
      int endAt = beginFrom + 40; 
      if(endAt > text.length()){ 
       endAt = text.length()-1; 
      } 
      String writableArea = text.substring(beginFrom, endAt); 
      canvas.drawText(writableArea, 100, 300+(i*100), paint); 
      canvas.save(); 
     } 
     return aBitmap; 
    } 

    private int calculateLines(String text){ 
     if(!TextUtils.isEmpty(text)){ 
      int lines = text.length()/40; 
      return lines; 
     } 
     return 1; 
    } 
+0

只需使用'android.text.Layout' – pskink

+0

@pskink你能解释一下吗? – Ichthyocentaurs

+0

用它来绘制'Canvas'上的Looong文本,不需要''计算线条,然后逐行写入'',而不是只创建一个'Layout'实例,并在'Canvas'上绘制它' – pskink

回答

1

您传递quotecalculateLines,你只是做什么,如果它不是空的,但是,你用mQuotelength那里。我认为这种混乱是你的问题的原因。您需要确保您通过的值是您想要传递的值,并在计算中使用quotelength而不是mQuotelength

+0

mQuote和报价是相同的。只是一个格式错误。 – Ichthyocentaurs

+0

@Iththyocentaurs什么是引用,它是如何初始化的,当方法被调用时它的值是什么? –

+0

prepareImageWithText(String text),接收文本作为输入。并调用calculateLines()将其作为输入。 – Ichthyocentaurs

2
for(int i=0; i<calculateLines(quote); i++) { 

if(endAt > text.length()){ 

这两行需要你的关注。 “文本”和“报价”是相同的字符串吗?

+0

他们是一样的东西,只是一个格式错误。我想我现在已经解决了这个问题。 – Ichthyocentaurs

+0

@Iththyocentaurs不是格式错误。你需要解释你的问题,否则我们尝试帮助你是不明智的。 –

+0

真的很抱歉混淆,我修正了变量名。但真正的问题是不正确的循环迭代次数的计算。 – Ichthyocentaurs