4

我正在做一个图形代码编辑器,我可以通过拖动来修改常量。我想用蓝色矩形突出显示代码中的命令,使左右边框位于字符中间,但在某些情况下蓝色矩形仍然未对齐:

突出问题

我的想法是首先计算字符宽度和字符空间,然后将它们乘以我的命令在文本中的位置。

val mCodePaint = new TextPaint()
mCodePaint.setTypeface(Typeface.MONOSPACE)
mCodePaint.setAntiAlias(true)
mCodePaint.setSubpixelText(true)
mCodePaint.setColor(0xFF000000)
val dimText = new Rect()
val dimText1 = new Rect()
val dimText2 = new Rect()

final val s1 = "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW"
final val s2 = "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW"
// dimText1.width() = char_length * s1.length + space_between_chars*(s1.length-1)
// dimText2.width() = char_length * s2.length + space_between_chars*(s2.length-1)
def getCharWidth(): Float = {
  mCodePaint.getTextBounds(s1, 0, s1.length, dimText1)
  mCodePaint.getTextBounds(s2, 0, s2.length, dimText2)
  (dimText2.width() * (s1.length - 1) - dimText1.width() *(s2.length - 1))/(s1.length - s2.length)
}

def getIntercharWidth(): Float = {
  mCodePaint.getTextBounds(s1, 0, s1.length, dimText1)
  mCodePaint.getTextBounds(s2, 0, s2.length, dimText2)
  (dimText1.width * s2.length - dimText2.width * s1.length)/(s1.length - s2.length)
}

// The main function that draw the text
def drawRuleCode(canvas: Canvas, ...): Unit = {
  var char_width = getCharWidth() // At run time, equals 29
  var space_width = getIntercharWidth() // At run time, equals -10

  for(action <- ...) {
    ...
    val column = action.column
    val length = action.length
    val x1 = left_x+8 + column*char_width + (column-1)*space_width - 0.5f*space_width
    val x2 = x1 + length*char_width + (length-1)*space_width + 1*space_width
    rectFData.set(x1, y1, x2, y2)
    canvas.drawRoundRect(rectFData, 5, 5, selectPaint)
  }


  for(line <- ...) {
    ...
    canvas.drawText(s, left_x + 8, ..., mCodePaint)
  }

您对如何克服这个小对齐问题有任何想法吗?有时它会产生巨大的差异,尤其是当表达式很长时。

编辑:我绘制了计算的文本边界,实际上它们是错误的。文本略大于 getTextBounds 给出的矩形(紫线): 在此处输入图像描述

4

1 回答 1

1

我需要传递 scale 参数,而不是使用 getTextBounds,因为字体大小不会随画布线性缩放: 这里的解释

 var c = new Matrix()
 val c_array = new Array[Float](9)

// The main function that draw the text
def drawRuleCode(canvas: Canvas, ...): Unit = {
  var box_width = getBoxWidth()

  canvas.getMatrix(c)
  c.getValues(c_array)
  val scale = c_array(Matrix.MSCALE_X)  // Compute the current matrix scale
  var box_width = getBoxWidth(scale)

  for(action <- ...) {
    ...
    val column = action.column
    val length = action.length
    val x1 = left_x+8 + column*box_width
    val x2 = x1 + length*box_width
    rectFData.set(x1, y1, x2, y2)
    canvas.drawRoundRect(rectFData, 5, 5, selectPaint)
  }

def getBoxWidth(scale: Float): Float = {
  mCodePaint.setTextSize(fontSize * scale)
  val result = mCodePaint.measureText(s1).toFloat / s1.length / scale
  mCodePaint.setTextSize(fontSize )
  result
}
于 2013-03-22T12:32:17.407 回答