目的
完成画板demo的前期步骤
相关技术、及其使用
xml配置文件:创建SeekBar比较简单,但是不足之处在于当实现横屏的时候就比较麻烦
代码创建:代码创建SeekBar比较简单,能够很好地实现横竖屏切换。
2、创建Slider类继承于View
初始化线条,小圆点,进度条的画笔:
private void init(){
// 线条
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(lineColor);
linePaint.setStrokeWidth(lineSize);
//小圆点
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setColor(thumbColor);
circlePaint.setStyle(Paint.Style.FILL);
// 进度条
progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
progressPaint.setColor(progressColor);
progressPaint.setStrokeWidth(lineSize);
}
3、调用onDraw 方法进行横竖屏的画图
protected void onDraw(Canvas canvas) {
//canvas 画布
if(getWidth() > getHeight()){
//横着
canvas.drawLine(0,getHeight()/2,getWidth(),getHeight()/2,linePaint);
if(position > 0){
//画进度条背景
canvas.drawLine(0,getHeight()/2,getWidth(),getHeight()/2,progressPaint);
}
cy = getHeight()/2 ;
radius = getHeight()/thumbScale;
//确定cx的值
if(position < radius){
cx = radius;
}else if(position > getWidth()- radius){
cx = getWidth() - radius;
}else {
cx = (int)position;
}
}else {
//竖着
canvas.drawLine(getWidth()/2,0,getWidth()/2,getHeight(),linePaint);
if(position>0){
canvas.drawLine(getWidth()/2,0,getWidth()/2,position,progressPaint);
}
cx = getWidth()/2;
radius = getWidth()/thumbScale;
//确定中点cy的值
if(position < radius){
cy = radius;
}else if(position > getHeight() - radius){
cy = getHeight() - radius;
}else {
cy = (int)position;
}
}
//画小圆点
if(style == SLIDER){
canvas.drawCircle(cx,cy,radius,circlePaint);
}
}
4、通过onTouchEvent方法来实现进度条随着触摸位置的改变:
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
//小圆点放大
thumbScale = 2;
if(getWidth() > getHeight()){
//横着 getWidth 表示得到LinearLayout的大小 y不变 x 改变
position = event.getX();
}else {
//竖着 x 不变 y 改变
position = event.getY();
if(position < 0){
position=0;
}else if(position > getHeight()){
position = getHeight();
}
}
callBake();
break;
case MotionEvent.ACTION_MOVE:
//横竖两种情况
//获取当前触摸点的值 x y
if(getWidth() > getHeight()){
//横着 getWidth 表示得到LinearLayout的大小 y不变 x 改变
position = event.getX();
}else {
//竖着 x 不变 y 改变
position = event.getY();
if(position < 0){
position=0;
}else if(position > getHeight()){
position = getHeight();
}
}
callBake();
break;
case MotionEvent.ACTION_UP:
thumbScale = 4;
break;
}
if(style == SLIDER){
//重新绘制
invalidate();
}
return true;
}
5、写一个获取进度值的方法callback():
private void callBake(){
if(onSliderChangeListener != null){
if(getWidth() > getHeight()){
progress = position / getWidth();
}else {
progress = position / getHeight();
}
onSliderChangeListener.progressChanged(progress*max);
}
}
6、定义接口和监听器来监听Slider改变值:
public void setMax(int max) {
this.max = max;
}
public interface OnSliderChangeListener{
void progressChanged(float progress);
}
public void setOnSliderChangeListener(OnSliderChangeListener onSliderChangeListener) {
this.onSliderChangeListener = onSliderChangeListener;
}
PS
今天画板的前期布局主要是进度条的代码设置,进一步的学习了通过代码画图Paint。