简体   繁体   中英

How android set custom font in canvas?

hi i want to change my font size by using paint, canvas in android. My code is here. how can i do this?

public class MainActivity extends Activity 

{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
Canvas canvas = new Canvas();
Typeface tf = Typeface.createFromAsset(getAssets(), "RECOGNITION.ttf");
     Paint paint = new Paint();
     paint.setTypeface(tf);
     canvas.drawText("Lorem ipsum", 0, 0, paint);


}
}

can any body help me to solve problem? i read some tutorials but not under stand. i have read some post of Stack,facing some problems.

create "fonts" folder under "assets" folder. After that put your font file in "fonts" folder and write below code.

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

Use this:

Typeface tf = Typeface.createFromAsset(getAssets(),"RECOGNITION.ttf");
   Paint paint = new Paint();
   paint.setTypeface(tf);
   canvas.drawText("Sample text in bold RECOGNITION",0,0,paint);

Full setup text in a custom view:

    TextPaint textPaint = new TextPaint();
    Typeface tf =Typeface.createFromAsset(getContext().getAssets(),"fonts/BungeeSpice-Regular.ttf");
    textPaint.setTypeface(tf);
    textPaint.setStrokeWidth(7);
    textPaint.setTextSize(Tool.convertSpToPx(getContext(), 30));
    textPaint.setAntiAlias(true);
    textPaint.setPathEffect(null);
    textPaint.setColor(getResources().getColor(R.color.green, null));

Use the next:

 Paint paint = new Paint();
 paint.setTypeface(tf);
 paint.setTextSize(yourTextSize);
 canvas.drawText("Lorem ipsum", 0, 0, paint);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM