view 画出一个形状,并在里面添加内容+文本居中

activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <lianxi.jdt.Circle
        android:layout_width="100dp"
        android:layout_height="100dp" />

</RelativeLayout>

 Circle.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by lenovo on 2017/11/01.
 */

public class Circle extends View{

    private Paint paint = new Paint();
    public Circle(Context context) {
        super(context);
    }

    public Circle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Circle(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //整体的颜色
        //canvas.drawColor(Color.YELLOW);

        paint.setColor(Color.YELLOW);
//正方形
 canvas.drawRect(0,0,200,200,paint);
        //圆形
//canvas.drawCircle(200/2,200/2,100,paint);

// measureText 测量字符串的宽度
float textWidth = paint.measureText("123");
Rect rextText = new Rect();
//        rextText.height() 获取字符串的高度
 paint.getTextBounds("123", 0, "123".length(), rextText);
 int x = getWidth()/2-rextText.width()/2;
 int y = getHeight()/2+rextText.height()/2;
 paint.setTextSize(15);
 paint.setColor(Color.BLACK);
 canvas.drawText("123",x,y,paint);

}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值