美文网首页UI效果
Android自定义view绘制文字四周边框

Android自定义view绘制文字四周边框

作者: Amy木婉清 | 来源:发表于2022-09-03 22:06 被阅读0次

文字支持四边框案例:
Activity

package com.example.borde;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

@SuppressLint("AppCompatCustomView")
public class BordeTestView extends TextView {
    public BordeTestView(Context context) {
        super(context);
    }
    public BordeTestView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    private int sroke_width = 1;
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        //  将边框设为红色
        paint.setColor(android.graphics.Color.RED);
        //  画TextView的4个边
        canvas.drawLine(0, 0, this.getWidth() - sroke_width, 0, paint);
        canvas.drawLine(0, 0, 0, this.getHeight() - sroke_width, paint);
        canvas.drawLine(this.getWidth() - sroke_width, 0, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
        canvas.drawLine(0, this.getHeight() - sroke_width, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
        super.onDraw(canvas);
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">

    <com.example.borde.BordeTestView
        android:layout_width="180dp"
        android:layout_height="260dp"
        android:text="测试文字边框"
        android:gravity="center"
        />

</LinearLayout>

相关文章

网友评论

    本文标题:Android自定义view绘制文字四周边框

    本文链接:https://www.haomeiwen.com/subject/bocpirtx.html