android - 如何在绘画对象中设置自定义字体?

android - how to set custom typeface in paint object?

我想用 Paint 画点东西,这是我的代码:

    Paint mMonthTitlePaint = new Paint();
    mMonthTitlePaint.setFakeBoldText(true);
    mMonthTitlePaint.setAntiAlias(true);
    mMonthTitlePaint.setTextSize(MONTH_LABEL_TEXT_SIZE);
    mMonthTitlePaint.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/iran_sans_.ttf"));
   mMonthTitlePaint.setColor(mDayTextColor);
   mMonthTitlePaint.setTextAlign(Align.CENTER);
   mMonthTitlePaint.setStyle(Style.FILL);

但它不起作用,字体不适用于绘画对象。我的问题在哪里?如何解决?

这是我的 onDraw :

@Override
protected void onDraw(Canvas canvas) {
    drawMonthNums(canvas);
}

和 drawMonthNums :

protected void drawMonthNums(Canvas canvas) {
        int y = (((mRowHeight + MINI_DAY_NUMBER_TEXT_SIZE) / 2) - DAY_SEPARATOR_WIDTH)
                + getMonthHeaderSize();
        final float dayWidthHalf = (mWidth - mEdgePadding * 2) / (mNumDays * 2.0f);
        int j = findDayOffset();
        for (int dayNumber = 1; dayNumber <= mNumCells; dayNumber++) {
            final int x = (int)((2 * j + 1) * dayWidthHalf + mEdgePadding);

            int yRelativeToDay = (mRowHeight + MINI_DAY_NUMBER_TEXT_SIZE) / 2 - DAY_SEPARATOR_WIDTH;

            final int startX = (int)(x - dayWidthHalf);
            final int stopX = (int)(x + dayWidthHalf);
            final int startY = y - yRelativeToDay;
            final int stopY = startY + mRowHeight;

            drawMonthDay(canvas, mYear, mMonth, dayNumber, x, y, startX, stopX, startY, stopY);

            j++;
            if (j == mNumDays) {
                j = 0;
                y += mRowHeight;
            }
        }
    }

最后这是我的资产文件夹:

试试这个:

    Typeface tf =Typeface.createFromAsset(getAssets(),"fonts/iran_sans_.ttf");
   Paint paint = new Paint();
   paint.setTypeface(tf);
   canvas.drawText("Sample text",0,0,paint);

您也可以使用 Textpaint class 代替 Paint

   TextPaint textPaint = new TextPaint();
    textPaint.setTextSize(20);
    textPaint.setTextAlign(Paint.Align.LEFT);
    textPaint.setColor(Color.WHITE);
    Typeface tf =Typeface.createFromAsset(getAssets(),"fonts/iran_sans_.ttf");
    textPaint.setTypeface(tf);

看到这个:https://developer.android.com/reference/android/text/TextPaint.html