2015-04-07 173 views
0

我已创建自定义视图,其显示了许多在不同的矩形框的数字:自定义创建的视图

protected void onDraw(Canvas canvas){ 
    Rect rect = new Rect(20, 20, 170, 220); 

    int xx = rect.left + 12; 
    int yy = (rect.bottom - 25); 

    int yyy = (rect.bottom +10); 
    int xxx = (rect.left-10); 

    for (int i = counter,j=0; i >= 0; i--,j++) { 
     // Drawing the rectangle and using the rectangle as reference, drawing the digit. 
     drawColoredDigit(canvas, rect, String.valueOf(digits[i]),xx,yy); 
     // Updating the reference values for the rectangle, and in turn for the digits inside the reference. 
     rect.left += (20 + 150); 
     rect.right += (20 + 150); 
     xx = (rect.left+ 20); 
     xxx = (rect.left - 20); 

     if(((counter-j)%3==0)&&(counter!=j)) 
     { 
      canvas.drawText(",",xxx,yyy,commaPaint); 
      rect.left += 20; 
      rect.right += 20; 
      xx = (rect.left + 20); 
     } 

    } 
} 

private void drawColoredDigit(Canvas canvas, Rect rect, String digit, int xx, int yy) { 
    canvas.drawRect(rect, widgetPaint); 
    canvas.drawText(digit, xx, yy, textPaint); 
} 

enter image description here

onDraw()的代码如下给出有没有办法让这段代码更具动态性,以便根据数字的长度来选择渲染数字的矩形的大小。然后根据矩形的大小选择数字的大小,然后渲染。 也需要处理各种设备上的像素处理。 基本上试图使视图更具动态性。

回答

0

我已经看到一些实现漂浮在TextView的周围,它会自动调整文本的大小以适应视图的大小。我的建议是从其中一个开始,并在文本上使用跨度,而不是试图自己绘制矩形和事物。查看ForegroundColorSpanBackgroundColorSpan,并使用SpannableString将跨度附加到文本。