5.8

所花时间(包括上课):1.5

打码量(行):230

博客量(篇):1

了解到知识点:学习绘制文本

 

 package com.example.myapp;

 

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Typeface;

import android.util.AttributeSet;

import android.view.View;

 

import androidx.annotation.Nullable;

 

public class TextDrawingView extends View {

 

    private Paint paint;

 

    public TextDrawingView(Context context) {

        super(context);

        init();

    }

 

    public TextDrawingView(Context context, @Nullable AttributeSet attrs) {

        super(context, attrs);

        init();

    }

 

    public TextDrawingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

        init();

    }

 

    private void init() {

        paint = new Paint();

        paint.setColor(Color.BLUE);

        paint.setTextSize(50f);

        paint.setTypeface(Typeface.SANS_SERIF);

        paint.setTextAlign(Paint.Align.LEFT);

    }

 

    @Override

    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

 

        // 绘制文本

        String text = "Hello, Android!";

        canvas.drawText(text, 100, 100, paint);

 

        // 改变文本颜色

        paint.setColor(Color.RED);

        canvas.drawText(text, 100, 200, paint);

 

        // 改变文本对齐方式

        paint.setTextAlign(Paint.Align.CENTER);

        canvas.drawText(text, canvas.getWidth() / 2, 300, paint);

 

        // 绘制旋转文本

        paint.setColor(Color.GREEN);

        canvas.save();

        canvas.rotate(-45, 200, 400);

        canvas.drawText(text, 200, 400, paint);

        canvas.restore();

    }

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

 

    <com.example.myapp.TextDrawingView

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

 

</RelativeLayout>

posted @ 2024-05-08 21:13  赵千万  阅读(2)  评论(0编辑  收藏  举报