自定义View

目录

自定义View
自定义View之Canvas
自定义View之Paint

概述

自定义属性

声明属性

使用declare-styleable声明属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="enableOnPad" format="boolean" />
<attr name="supportDeviceType" format="reference"/>
<!-- 如果有通用的属性,可以抽离出来 -->
<declare-styleable name="ExTextView">
<attr name="enableOnPad"/>
<attr name="supportDeviceType"/>
</declare-styleable>

<declare-styleable name="ExEditText">
<attr name="enableOnPad"/>
<attr name="supportDeviceType"/>
<attr name="line_color" format="color" />
<attr name="line_stroke_height" format="dimension"/>
</declare-styleable>
</resources>


使用属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


xml中使用属性

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto" //自动查找
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<CustomView
android:layout_width="match_parent"
android:layout_height="60dp"
app:line_color=""
/>
</RelativeLayout>

public class CustomView extends View {

public DottedLineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 根据Style拿到TypedArray
TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.ExEditText);
mLineColor = array.getColor(R.styleable.ExEditText_line_color, getResources().getColor(R.color.Red));
mLineStrokeHeight = array.getDimension(R.styleable.ExEditText_line_stroke_height, dp2px(getContext(), 1));
array.recycle();
}
}

Read More

自定义View之Canvas

目录

自定义View
自定义View之Canvas
自定义View之Paint

API

颜色填充

1
2
3
4
canvas.drawColor(Color.BLACK);
canvas.drawColor(Color.parse("#88880000"); // 半透明红色
canvas.drawRGB(100, 200, 100);
canvas.drawARGB(100, 100, 200, 100);

画圆

1
2
3
4
5
6
7
8

/**
前两个参数 centerX centerY 是圆心的坐标,第三个参数 radius 是圆的半径,单位都是像素
*/
drawCircle(float centerX, float centerY, float radius, Paint paint)

canvas.drawCircle(300, 300, 200, paint);

Read More

自定义View之Paint

目录

自定义View
自定义View之Canvas
自定义View之Paint

API

颜色设置

1
2
3
4
5
6
7
8
9
10
11
12

setColor(int color)

paint.setColor(Color.parseColor("#009688"));
canvas.drawRect(30, 30, 230, 180, paint);


setARGB(int a, int r, int g, int b)

paint.setARGB(100, 255, 0, 0);
canvas.drawRect(0, 0, 200, 200, paint);

Shader设置

在 Android 的绘制里使用 Shader ,并不直接用 Shader 这个类,而是用它的几个子类。具体来讲有:

Read More