0
点赞
收藏
分享

微信扫一扫

android自定义控件——深入篇,android应用开发实战演练音乐播放器

纽二 2022-02-03 阅读 52

super.onDraw(canvas);

canvas.drawColor(Color.RED);

// 设置字体在画板的位置

// paint.descent() - paint.ascent() - getPaddingTop()使字体位于画板的中央

canvas.drawText(text, getPaddingLeft(),

paint.descent() - paint.ascent() - getPaddingTop(), paint);

}

// 定义一个方法,对画笔的各属性进行设置

private void initPaint() {

paint = new Paint();

paint.setColor(color);

paint.setTextSize(size);

paint.setAntiAlias(true);

paint.setStyle(Style.STROKE);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

// TODO Auto-generated method stub

// 计算控件的大小

// 规定一个变量type 若为1 ,计算宽的大小,若为2,计算长的大小

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

// 设置所测量控件的大小

setMeasuredDimension(meaSure(widthMeasureSpec, 1),

meaSure(heightMeasureSpec, 2));

}

public int meaSure(int spec, int type) {

// 首先获取定义的类型

int mode = MeasureSpec.getMode(spec);

// 获取系统默认的大小

int whsize = MeasureSpec.getSize(spec);

switch (mode) {

// 包裹内容

case MeasureSpec.AT_MOST:

int padding = 0;

int measureText = 0;

if (type == 1) {

padding = getPaddingLeft() + getPaddingRight();

measureText = (int) paint.measureText(text);

} else {

padding = getPaddingBottom() + getPaddingTop();

measureText = (int) (paint.descent() - paint.ascent());

}

// 包裹文字宽的实际长度

whsize = padding + measureText;

break;

default:

break;

}

return whsize;

}

}

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

然后就是在MainActivity.XML中进行各属性的设值了。代码如下:

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

xmlns:tools=“http://schemas.android.com/tools”

xmlns:app=“http://schemas.android.com/apk/res-auto”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

举报

相关推荐

0 条评论