自定义View总结
package com.bs.gnc.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("",0,0,new Paint());
setTypeface(Typeface typeface)
paint.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Satisfy-Regular.ttf"));
setFakeBoldText(boolean fakeBoldText)
setStrikeThruText(boolean strikeThruText)
setUnderlineText(boolean underlineText)
setTextSkewX(float skewX)
setTextScaleX(float scaleX)
setLetterSpacing(float letterSpacing)
setFontFeatureSettings(String settings)
setTextAlign(Paint.Align align)
setSubpixelText(boolean subpixelText)
float getFontSpacing()
}
1.让父类去帮助我计算结果
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
int width = getMeasuredWidth();
int result = width<height?width:height;
setMeasuredDimension(result,result);
}
2.完全自己计算view的尺寸
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measureWidth = 0;
int measureHeight = 0;
measureWidth = resolveSize(measureWidth,widthMeasureSpec);
measureHeight = resolveSize(measureHeight,heightMeasureSpec);
setMeasuredDimension(measureWidth,measureHeight);
}
}
1.对绘制的内容进行平移,旋转,缩放,等操作时的api调用顺序为Canvas.save() ,Canvas.translate() ,Canvas.restore()
2. getTextBounds: 它测量的是文字的显示范围(关键词:显示)measureText(): 它测量的是文字绘制时所占用的宽度(关键词:占用)导致了 measureText() 比 getTextBounds() 测量出的宽度要大一些
3. 绘制顺序
11.背景
22.主体(onDraw())
33.子 View(dispatchDraw())
44.滑动边缘渐变和滑动条
55.前景
4. 设置文本的对齐方式和换行
41. StaticLayout 的构造方法是 StaticLayout(CharSequence source, TextPaint paint, int width, Layout.Alignment align, float spacingmult, float spacingadd, boolean includepad),其中参数里:width 是文字区域的宽度,文字到达这个宽度后就会自动换行;align 是文字的对齐方向;spacingmult 是行间距的倍数,通常情况下填 1 就好;spacingadd 是行间距的额外增加值,通常情况下填 0 就好; includepad 是指是否在文字上下添加额外的空间,来避免某些过高的字符的绘制出现越界。