固定比例绘制画布

时间:2018-08-26 13:11:11

标签: android canvas android-canvas

我有一个使用canvas onDraw方法绘制的按钮。按钮本身可能会根据设备而改变大小,但是我希望在内部绘制的文本保持一致,即使用户在设置中设置了不同的屏幕大小或字体大小也是如此。这就是为什么我以像素为单位。

@Override
public void onDraw(Canvas canvas) {
    // 1. draw background
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(colorBg);
    canvas.drawRect(padding, padding, w-padding, h-padding, paint);

    // 2. draw border
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(colorBorder);
    canvas.drawRect(padding, padding, w-padding, h-padding, paint);

    // 3. draw text
    int fontSizeTextNew = canvas.getHeight() / 100 * 19;
    int fontSizePaddingNew = canvas.getHeight() / 100 * 19;

    textPaint.setTextSize(fontSizeTextNew);
    textPaint.setShader(blackShader);
    textPaint.setTypeface(Typeface.DEFAULT);
    textPaint.getTextBounds(
            prefTitle, // text
            0, // start
            prefTitle.length(), // end
            rectangle // bounds
    );

    canvas.drawText(
            prefTitle,
            canvas.getWidth()/2,
            Math.abs(rectangle.height()) + padding + fontSizePaddingNew,
            textPaint
    );

    // 4. draw icon
    int fontSizeIconNew = canvas.getHeight() / 100 * 55;
    String str = prefIcon;
    textPaint.setTypeface(awesomeFont);
    textPaint.setTextSize(fontSizeIconNew);
    textPaint.setShader(yellowShader);
    // center for the text
    // https://stackoverflow.com/questions/11120392/android-center-text-on-canvas
    int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
    canvas.drawText(
            str,
            canvas.getWidth()/2,
            Math.abs(yPos) + fontSizeIconPadding,
            textPaint
    );
}

这19%的内容现在看起来不错,但在各种屏幕上看起来都不同。您如何解决此问题?您将如何解决这个问题?

Button1就是这样

0 个答案:

没有答案