Android自定义控件绘图基础
首先继承View,并进行相关初始化操作。
对于DrawAllocation的Lint警告提示:
不要在View绘制和做布局操作的时候实例化数据,将创建对象等这些分配内存资源和会引起垃圾回收机制的操作在onDraw/onLayout之前进行,例如设置为全局变量,提取一个init()方法来实例化对象。
因为在View及其子类的onDraw(Canvas canvas)方法,会实时调用以更新界面,会频繁的创建对象和进行垃圾回收,垃圾回收的GC线程会抢占CPU资源影响UI的显示性能,这样一个显示很顺畅的用户界面就会因对象分配引起的一些垃圾回收机制进行短暂的停滞。
public class BasisView extends View {
private Paint mPaint;
private RectF mRectF;
private Rect mRect;
private Bitmap mBitmap;
private Path mPath;
public BasisView(Context context) {
this(context, null);
}
public BasisView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BasisView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* Lint警告:
* Avoid object allocations during draw/layout operations (preallocate and reuse instead)
* Issue: Looks for memory allocations within drawing code
* Id: DrawAllocation
* You should avoid allocating objects during a drawing or layout operation. These are called frequently, so a smooth UI can be interrupted by garbage collection pauses caused by the object allocations.
* The way this is generally handled is to allocate the needed objects up front and to reuse them for each drawing operation.
* Some methods allocate memory on your behalf (such as Bitmap.create), and these should be handled in the same way.
*/
private void init() {
mPaint = new Paint();
mRectF = new RectF();
mRect = new Rect();
mBitmap = getBitmap(getContext(), R.mipmap.ic_launcher);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
0、画笔Paint
文本相关
setColor(@ColorInt int color) 设置画笔颜色
s