/**
   * Request a different font size. Will make call to parentChanged() to make sure we resize PTY if
   * needed.
   */
  /* package */ final void setFontSize(float size) {
    if (size <= 0.0) return;

    defaultPaint.setTextSize(size);
    fontSize = size;

    // read new metrics to get exact pixel dimensions
    FontMetrics fm = defaultPaint.getFontMetrics();
    charTop = (int) Math.ceil(fm.top);

    float[] widths = new float[1];
    defaultPaint.getTextWidths("X", widths);
    charWidth = (int) Math.ceil(widths[0]);
    charHeight = (int) Math.ceil(fm.descent - fm.top);

    // refresh any bitmap with new font size
    if (parent != null) parentChanged(parent);

    for (FontSizeChangedListener ofscl : fontSizeChangedListeners) ofscl.onFontSizeChanged(size);

    host.setFontSize((int) fontSize);
    manager.hostdb.updateFontSize(host);

    forcedSize = false;
  }
Example #2
0
  @Override
  public void draw(Canvas canvas) {
    canvas.drawRoundRect(mRectF, mRadius, mRadius, mBorderPaint);

    Path path = new Path();
    path.moveTo(mRectF.right - 2 * mOffsetY - mOffsetX, mRectF.bottom);
    path.lineTo(mRectF.right - (2 * mOffsetY + mRadius) / 2 - mOffsetX, mRectF.bottom + mOffsetY);
    path.lineTo(mRectF.right - mRadius - mOffsetX, mRectF.bottom);

    float x = 0;
    float y = mRectF.centerY();

    String text = "One Piece";
    float[] characterWidths = new float[text.length()];
    int characterNum = mTextPaint.getTextWidths(text, characterWidths);

    float textWidth = 0f;
    for (int i = 0; i < characterNum; i++) {
      textWidth += characterWidths[i];
    }
    canvas.save();
    canvas.translate(mRectF.width() / 2 - textWidth / 2, 0);
    canvas.drawText("one piece", x, y, mTextPaint);

    canvas.restore();
    canvas.drawPath(path, mBorderPaint);
  }
Example #3
0
  /**
   * Draws the chart legend.
   *
   * @param canvas the canvas to paint to
   * @param renderer the series renderer
   * @param titles the titles to go to the legend
   * @param left the left X value of the area to draw to
   * @param right the right X value of the area to draw to
   * @param y the y value of the area to draw to
   * @param width the width of the area to draw to
   * @param height the height of the area to draw to
   * @param legendSize the legend size
   * @param paint the paint to be used for drawing
   * @param calculate if only calculating the legend size
   * @return the legend height
   */
  protected int drawLegend(
      Canvas canvas,
      DefaultRenderer renderer,
      String[] titles,
      int left,
      int right,
      int y,
      int width,
      int height,
      int legendSize,
      Paint paint,
      boolean calculate) {
    float size = 32;
    if (renderer.isShowLegend()) {
      float currentX = left;
      float currentY = y + height - legendSize + size;
      paint.setTextAlign(Align.LEFT);
      paint.setTextSize(renderer.getLegendTextSize());
      int sLength = Math.min(titles.length, renderer.getSeriesRendererCount());
      for (int i = 0; i < sLength; i++) {
        final float lineSize = getLegendShapeWidth(i);
        String text = titles[i];
        if (titles.length == renderer.getSeriesRendererCount()) {
          paint.setColor(renderer.getSeriesRendererAt(i).getColor());
        } else {
          paint.setColor(Color.LTGRAY);
        }
        float[] widths = new float[text.length()];
        paint.getTextWidths(text, widths);
        float sum = 0;
        for (float value : widths) {
          sum += value;
        }
        float extraSize = lineSize + 10 + sum;
        float currentWidth = currentX + extraSize;

        if (i > 0 && getExceed(currentWidth, renderer, right, width)) {
          currentX = left;
          currentY += renderer.getLegendTextSize();
          size += renderer.getLegendTextSize();
          currentWidth = currentX + extraSize;
        }
        if (getExceed(currentWidth, renderer, right, width)) {
          float maxWidth = right - currentX - lineSize - 10;
          if (isVertical(renderer)) {
            maxWidth = width - currentX - lineSize - 10;
          }
          int nr = paint.breakText(text, true, maxWidth, widths);
          text = text.substring(0, nr) + "...";
        }
        if (!calculate) {
          drawLegendShape(canvas, renderer.getSeriesRendererAt(i), currentX, currentY, i, paint);
          drawString(canvas, text, currentX + lineSize + 5, currentY + 5, paint);
        }
        currentX += extraSize;
      }
    }
    return Math.round(size + renderer.getLegendTextSize());
  }
 public int getTextWidth(Paint paint, String str) {
   int iRet = 0;
   if (str != null && str.length() > 0) {
     int len = str.length();
     float[] widths = new float[len];
     paint.getTextWidths(str, widths);
     for (int j = 0; j < len; j++) {
       iRet += (int) Math.ceil(widths[j]);
     }
   }
   return iRet;
 }
 public static int getWidthofString(String str, Paint paint) {
   if (str != null && str.equals("") == false && paint != null) {
     int strLength = str.length();
     int result = 0;
     float[] widths = new float[strLength];
     paint.getTextWidths(str, widths);
     for (int i = 0; i < strLength; i++) {
       result += widths[i];
     }
     return (int) result;
   }
   return 0;
 }
Example #6
0
 private String[] getTextLines(Paint paint, String text, int max_length) {
   float[] widths = new float[text.length()];
   paint.getTextWidths(text, widths);
   StringBuilder builder = new StringBuilder();
   int length = 0;
   for (int i = 0; i < widths.length; i++) {
     length += widths[i];
     if (length <= max_length) {
       builder.append(text.charAt(i));
     } else {
       builder.append("&");
       builder.append(text.charAt(i));
       length = 0;
     }
   }
   return builder.toString().split("&");
 }
  private int fontSizeCompare(float size, int cols, int rows, int width, int height) {
    // read new metrics to get exact pixel dimensions
    defaultPaint.setTextSize(size);
    FontMetrics fm = defaultPaint.getFontMetrics();

    float[] widths = new float[1];
    defaultPaint.getTextWidths("X", widths);
    int termWidth = (int) widths[0] * cols;
    int termHeight = (int) Math.ceil(fm.descent - fm.top) * rows;

    Log.d(
        "fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight));

    // Check to see if it fits in resolution specified.
    if (termWidth > width || termHeight > height) return 1;

    if (termWidth == width || termHeight == height) return 0;

    return -1;
  }
  // 计算文字行数和总宽
  private void GetTextInfo() {
    Log.v("TextViewVertical", "GetTextInfo");
    char ch;
    int h = 0;
    paint.setTextSize(mFontSize);
    // 获得字宽
    if (mLineWidth == 0) {
      float[] widths = new float[1];
      paint.getTextWidths("正", widths); // 获取单个汉字的宽度
      mLineWidth = (int) Math.ceil((widths[0] * 2) * 1.1 + 2);
    }

    FontMetrics fm = paint.getFontMetrics();
    mFontHeight = (int) (Math.ceil(fm.descent - fm.top) * 0.9); // 获得字体高度
    // 计算文字行数
    mRealLine = 0;
    for (int i = 0; i < this.TextLength; i++) {
      ch = this.text.charAt(i);
      if (ch == '\n') {
        mRealLine++; // 真实的行数加一
        h = 0;
      } else {
        h += mFontHeight;
        if (h > this.mTextHeight) {
          mRealLine++; // 真实的行数加一
          i--;
          h = 0;
        } else {
          if (i == this.TextLength - 1) {
            mRealLine++; // 真实的行数加一
          }
        }
      }
    }
    mRealLine++; // 额外增加一行
    mTextWidth = mLineWidth * mRealLine; // 计算文字总宽度
    measure(mTextWidth, getHeight()); // 重新调整大小
    layout(getLeft(), getTop(), getLeft() + mTextWidth, getBottom()); // 重新绘制容器
  }
  private void assertGetTextRunAdvances(
      String str,
      int start,
      int end,
      int contextStart,
      int contextEnd,
      boolean isRtl,
      boolean compareWithOtherMethods) {
    Paint p = new Paint();

    final int count = end - start;
    final float[][] advanceArrays = new float[4][count];

    final float advance =
        p.getTextRunAdvances(str, start, end, contextStart, contextEnd, isRtl, advanceArrays[0], 0);

    char chars[] = str.toCharArray();
    final float advance_c =
        p.getTextRunAdvances(
            chars,
            start,
            count,
            contextStart,
            contextEnd - contextStart,
            isRtl,
            advanceArrays[1],
            0);
    assertEquals(advance, advance_c, 1.0f);

    for (int c = 1; c < count; ++c) {
      final float firstPartAdvance =
          p.getTextRunAdvances(
              str, start, start + c, contextStart, contextEnd, isRtl, advanceArrays[2], 0);
      final float secondPartAdvance =
          p.getTextRunAdvances(
              str, start + c, end, contextStart, contextEnd, isRtl, advanceArrays[2], c);
      assertEquals(advance, firstPartAdvance + secondPartAdvance, 1.0f);

      final float firstPartAdvance_c =
          p.getTextRunAdvances(
              chars, start, c, contextStart, contextEnd - contextStart, isRtl, advanceArrays[3], 0);
      final float secondPartAdvance_c =
          p.getTextRunAdvances(
              chars,
              start + c,
              count - c,
              contextStart,
              contextEnd - contextStart,
              isRtl,
              advanceArrays[3],
              c);
      assertEquals(advance, firstPartAdvance_c + secondPartAdvance_c, 1.0f);
      assertEquals(firstPartAdvance, firstPartAdvance_c, 1.0f);
      assertEquals(secondPartAdvance, secondPartAdvance_c, 1.0f);

      for (int i = 1; i < advanceArrays.length; i++) {
        for (int j = 0; j < count; j++) {
          assertEquals(advanceArrays[0][j], advanceArrays[i][j], 1.0f);
        }
      }

      // Compare results with measureText, getRunAdvance, and getTextWidths.
      if (compareWithOtherMethods && start == contextStart && end == contextEnd) {
        assertEquals(advance, p.measureText(str, start, end), 1.0f);
        assertEquals(
            advance, p.getRunAdvance(str, start, end, contextStart, contextEnd, isRtl, end), 1.0f);

        final float[] widths = new float[count];
        p.getTextWidths(str, start, end, widths);
        for (int i = 0; i < count; i++) {
          assertEquals(advanceArrays[0][i], widths[i], 1.0f);
        }
      }
    }
  }
Example #10
0
  boolean layout(LineLabel label, LabelIndex labels) {
    String txt = label.getText();
    Rule rule = label.getRule();
    Feature f = label.getFeature();
    Geometry g = label.getGeometry();

    LineString line = null;
    if (g instanceof MultiLineString) {
      // TODO: handle multiple lines
      if (g.getNumGeometries() == 1) {
        line = (LineString) g.getGeometryN(0);
      }
    } else {
      line = (LineString) g;
    }
    if (line == null) {
      return false;
    }

    Paint p = label.get(Paint.class, Paint.class);

    // compute the bounds of the label with no rotation
    Rect r = new Rect();
    p.getTextBounds(txt, 0, txt.length(), r);

    // map it to world coordinates
    RectF bounds = new RectF(r);
    tx.getCanvasToWorld().mapRect(bounds);

    // ignore label if its too long for the line

    if (line.getLength() < bounds.width()) {
      // ignore this label
      return false;
    }

    // reverse
    if (line.getPointN(0).getX() > line.getPointN(line.getNumPoints() - 1).getX()) {
      line = (LineString) line.reverse();
    }

    // compute width of individual letters
    float[] widths = new float[txt.length()];
    p.getTextWidths(txt, widths);

    // map the widths to world space
    float sum = 0;
    for (int i = 0; i < widths.length; i++) {
      RectF s = new RectF(0, 0, widths[i], 1);
      tx.getCanvasToWorld().mapRect(s);

      widths[i] = s.width();
      sum += s.width();
    }

    // TODO: properly figure out spacing between letters
    float space = tx.getCanvasToWorld().mapRadius(1);

    // allowable angle change in consecutive characters
    double maxAngleDelta = rule.number(f, TEXT_MAX_CHAR_ANGLE_DELTA, DEFAULT_MAX_ANGLE_CHAR_DELTA);

    //
    // sample points along the line for letters
    //
    List<LineSegment> path = new ArrayList<LineSegment>();

    LineSampler sampler = new LineSampler(line.getCoordinates());

    for (int i = 0; i < txt.length(); i++) {
      // get next point
      Coordinate c1 = sampler.sample();

      // advance by width of letter
      sampler.advance(widths[i]);

      // get point for end of letter
      Coordinate c2 = sampler.sample();

      if (c1 == null || c2 == null) {
        // ran out of room
        return false;
      }

      LineSegment seg = new LineSegment(c1, c2);

      // check angle made with previous segment
      if (i > 0) {
        LineSegment prev = path.get(i - 1);
        if (Math.abs(angle(seg) - angle(prev)) > maxAngleDelta) {
          return false;
        }
      }

      path.add(seg);
      sampler.advance(space);
    }

    label.setPath(path);
    label.setShape(toShape(path, bounds.height()));
    return labels.insert(label);
  }
Example #11
0
  // --Load Font--//
  // description
  //    this will load the specified font file, create a texture for the defined
  //    character range, and setup all required values used to render with it.
  // arguments:
  //    file - Filename of the font (.ttf, .otf) to use. In 'Assets' folder.
  //    size - Requested pixel size of font (height)
  //    padX, padY - Extra padding per character (X+Y Axis); to prevent overlapping characters.
  public boolean load(String file, int size, int padX, int padY) {

    // setup requested values
    fontPadX = padX; // Set Requested X Axis Padding
    fontPadY = padY; // Set Requested Y Axis Padding

    // load the font and setup paint instance for drawing
    Typeface tf = Typeface.createFromAsset(assets, file); // Create the Typeface from Font File
    Paint paint = new Paint(); // Create Android Paint Instance
    paint.setAntiAlias(true); // Enable Anti Alias
    paint.setTextSize(size); // Set Text Size
    paint.setColor(0xffffffff); // Set ARGB (White, Opaque)
    paint.setTypeface(tf); // Set Typeface

    // get font metrics
    Paint.FontMetrics fm = paint.getFontMetrics(); // Get Font Metrics
    fontHeight = (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); // Calculate Font Height
    fontAscent = (float) Math.ceil(Math.abs(fm.ascent)); // Save Font Ascent
    fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // Save Font Descent

    // determine the width of each character (including unknown character)
    // also determine the maximum character width
    char[] s = new char[2]; // Create Character Array
    charWidthMax = charHeight = 0; // Reset Character Width/Height Maximums
    float[] w = new float[2]; // Working Width Value
    int cnt = 0; // Array Counter
    for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character
      s[0] = c; // Set Character
      paint.getTextWidths(s, 0, 1, w); // Get Character Bounds
      charWidths[cnt] = w[0]; // Get Width
      if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width
      charWidthMax = charWidths[cnt]; // Save New Max Width
      cnt++; // Advance Array Counter
    }
    s[0] = CHAR_NONE; // Set Unknown Character
    paint.getTextWidths(s, 0, 1, w); // Get Character Bounds
    charWidths[cnt] = w[0]; // Get Width
    if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width
    charWidthMax = charWidths[cnt]; // Save New Max Width
    cnt++; // Advance Array Counter

    // set character height to font height
    charHeight = fontHeight; // Set Character Height

    // find the maximum size, validate, and setup cell sizes
    cellWidth = (int) charWidthMax + (2 * fontPadX); // Set Cell Width
    cellHeight = (int) charHeight + (2 * fontPadY); // Set Cell Height
    int maxSize = cellWidth > cellHeight ? cellWidth : cellHeight; // Save Max Size (Width/Height)
    if (maxSize < FONT_SIZE_MIN || maxSize > FONT_SIZE_MAX) // IF Maximum Size Outside Valid Bounds
    return false; // Return Error

    // set texture size based on max font size (width or height)
    // NOTE: these values are fixed, based on the defined characters. when
    // changing start/end characters (CHAR_START/CHAR_END) this will need adjustment too!
    if (maxSize <= 24) // IF Max Size is 18 or Less
    textureSize = 256; // Set 256 Texture Size
    else if (maxSize <= 40) // ELSE IF Max Size is 40 or Less
    textureSize = 512; // Set 512 Texture Size
    else if (maxSize <= 80) // ELSE IF Max Size is 80 or Less
    textureSize = 1024; // Set 1024 Texture Size
    else // ELSE IF Max Size is Larger Than 80 (and Less than FONT_SIZE_MAX)
    textureSize = 2048; // Set 2048 Texture Size

    // create an empty bitmap (alpha only)
    Bitmap bitmap =
        Bitmap.createBitmap(textureSize, textureSize, Bitmap.Config.ALPHA_8); // Create Bitmap
    Canvas canvas = new Canvas(bitmap); // Create Canvas for Rendering to Bitmap
    bitmap.eraseColor(0x00000000); // Set Transparent Background (ARGB)

    // calculate rows/columns
    // NOTE: while not required for anything, these may be useful to have :)
    colCnt = textureSize / cellWidth; // Calculate Number of Columns
    rowCnt = (int) Math.ceil((float) CHAR_CNT / (float) colCnt); // Calculate Number of Rows

    // render each of the characters to the canvas (ie. build the font map)
    float x = fontPadX; // Set Start Position (X)
    float y = (cellHeight - 1) - fontDescent - fontPadY; // Set Start Position (Y)
    for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character
      s[0] = c; // Set Character to Draw
      canvas.drawText(s, 0, 1, x, y, paint); // Draw Character
      x += cellWidth; // Move to Next Character
      if ((x + cellWidth - fontPadX) > textureSize) { // IF End of Line Reached
        x = fontPadX; // Set X for New Row
        y += cellHeight; // Move Down a Row
      }
    }
    s[0] = CHAR_NONE; // Set Character to Use for NONE
    canvas.drawText(s, 0, 1, x, y, paint); // Draw Character

    // generate a new texture
    int[] textureIds = new int[1]; // Array to Get Texture Id
    gl.glGenTextures(1, textureIds, 0); // Generate New Texture
    textureId = textureIds[0]; // Save Texture Id

    // setup filters for texture
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind Texture
    gl.glTexParameterf(
        GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); // Set Minification Filter
    gl.glTexParameterf(
        GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); // Set Magnification Filter
    gl.glTexParameterf(
        GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); // Set U Wrapping
    gl.glTexParameterf(
        GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); // Set V Wrapping

    // load the generated bitmap onto the texture
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // Load Bitmap to Texture
    gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); // Unbind Texture

    // release the bitmap
    bitmap.recycle(); // Release the Bitmap

    // setup the array of character texture regions
    x = 0; // Initialize X
    y = 0; // Initialize Y
    for (int c = 0; c < CHAR_CNT; c++) { // FOR Each Character (On Texture)
      charRgn[c] =
          new TextureRegion(
              textureSize,
              textureSize,
              x,
              y,
              cellWidth - 1,
              cellHeight - 1); // Create Region for Character
      x += cellWidth; // Move to Next Char (Cell)
      if (x + cellWidth > textureSize) {
        x = 0; // Reset X Position to Start
        y += cellHeight; // Move to Next Row (Cell)
      }
    }

    // create full texture region
    textureRgn =
        new TextureRegion(
            textureSize, textureSize, 0, 0, textureSize, textureSize); // Create Full Texture Region

    // return success
    return true; // Return Success
  }