转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/38513301
手机里设置闹钟需要选择时间,那个选择时间的控件就是滚动选择器,前几天用手机刷了MIUI,发现自带的那个时间选择器效果挺好看的,于是就自己仿写了一个,权当练手。先来看效果:
效果还行吧?实现思路就是自定义一个PickerView,单独滚动的是一个PickerView,显然上图中有分和秒的选择所以在布局里用了两个PickerView。由于这里不涉及到text的点击事件,所以只需要继承View就行了,直接把text用canvas画上去。PickerView的实现的主要难点:
难点1:
字体随距离的渐变。可以看到,text随离中心位置的距离变化而变化,这里变化的是透明度alpha和字体大小TexSize,这两个值我都设置了Max和Min值,通过其与中心点的距离计算scale。我用的是变化曲线是抛物线scale=1-ax^2(x<=Height/4),scale = 0(x>Height/4),a=(4/Height)^2。x就是距离View中心的偏移量。用图片表示如下:
难点2:
text的居中。绘制text的时候不仅要使其在x方向上居中,还要在y方向上居中,在x方向上比较简单,设置Paint的Align为Align.CENTER就行了,但是y方向上很蛋疼,需要计算text的baseline。
难点3:
循环滚动。为了解决循环滚动的问题我把存放text的List从中间往上下摊开,通过不断地moveHeadToTail和moveTailToHead使选中的text始终是list的中间position的值。
以上就是几个难点,了解了之后可以来看PickerView的代码了:
[java] view plain copy
- package com.jingchen.timerpicker;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Paint;
- import android.graphics.Paint.Align;
- import android.graphics.Paint.FontMetricsInt;
- import android.graphics.Paint.Style;
- import android.os.Handler;
- import android.os.Message;
- import android.util.AttributeSet;
- import android.view.MotionEvent;
- import android.view.View;
- /**
- * 滚动选择器
- *
- * @author chenjing
- *
- */
- public class PickerView extends View
- {
- public static final String TAG = "PickerView";
- /**
- * text之间间距和minTextSize之比
- */
- public static final float MARGIN_ALPHA = 2.8f;
- /**
- * 自动回滚到中间的速度
- */
- public static final float SPEED = 2;
- private List<String> mDataList;
- /**
- * 选中的位置,这个位置是mDataList的中心位置,一直不变
- */
- private int mCurrentSelected;
- private Paint mPaint;
- private float mMaxTextSize = 80;
- private float mMinTextSize = 40;
- private float mMaxTextAlpha = 255;
- private float mMinTextAlpha = 120;
- private int mColorText = 0x333333;
- private int mViewHeight;
- private int mViewWidth;
- private float mLastDownY;
- /**
- * 滑动的距离
- */
- private float mMoveLen = 0;
- private boolean isInit = false;
- private onSelectListener mSelectListener;
- private Timer timer;
- private MyTimerTask mTask;
- Handler updateHandler = new Handler()
- {
- @Override
- public void handleMessage(Message msg)
- {
- if (Math.abs(mMoveLen) < SPEED)
- {
- mMoveLen = 0;
- if (mTask != null)
- {
- mTask.cancel();
- mTask = null;
- performSelect();
- }
- } else
- // 这里mMoveLen / Math.abs(mMoveLen)是为了保有mMoveLen的正负号,以实现上滚或下滚
- mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
- invalidate();
- }
- };
- public PickerView(Context context)
- {
- super(context);
- init();
- }
- public PickerView(Context context, AttributeSet attrs)
- {
- super(context, attrs);
- init();
- }
- public void setOnSelectListener(onSelectListener listener)
- {
- mSelectListener = listener;
- }
- private void performSelect()
- {
- if (mSelectListener != null)
- mSelectListener.onSelect(mDataList.get(mCurrentSelected));
- }
- public void setData(List<String> datas)
- {
- mDataList = datas;
- mCurrentSelected = datas.size() / 2;
- invalidate();
- }
- public void setSelected(int selected)
- {
- mCurrentSelected = selected;
- }
- private void moveHeadToTail()
- {
- String head = mDataList.get(0);
- mDataList.remove(0);
- mDataList.add(head);
- }
- private void moveTailToHead()
- {
- String tail = mDataList.get(mDataList.size() - 1);
- mDataList.remove(mDataList.size() - 1);
- mDataList.add(0, tail);
- }
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
- {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- mViewHeight = getMeasuredHeight();
- mViewWidth = getMeasuredWidth();
- // 按照View的高度计算字体大小
- mMaxTextSize = mViewHeight / 4.0f;
- mMinTextSize = mMaxTextSize / 2f;
- isInit = true;
- invalidate();
- }
- private void init()
- {
- timer = new Timer();
- mDataList = new ArrayList<String>();
- mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
- mPaint.setStyle(Style.FILL);
- mPaint.setTextAlign(Align.CENTER);
- mPaint.setColor(mColorText);
- }
- @Override
- protected void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- // 根据index绘制view
- if (isInit)
- drawData(canvas);
- }
- private void drawData(Canvas canvas)
- {
- // 先绘制选中的text再往上往下绘制其余的text
- float scale = parabola(mViewHeight / 4.0f, mMoveLen);
- float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
- mPaint.setTextSize(size);
- mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
- // text居中绘制,注意baseline的计算才能达到居中,y值是text中心坐标
- float x = (float) (mViewWidth / 2.0);
- float y = (float) (mViewHeight / 2.0 + mMoveLen);
- FontMetricsInt fmi = mPaint.getFontMetricsInt();
- float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));
- canvas.drawText(mDataList.get(mCurrentSelected), x, baseline, mPaint);
- // 绘制上方data
- for (int i = 1; (mCurrentSelected - i) >= 0; i++)
- {
- drawOtherText(canvas, i, -1);
- }
- // 绘制下方data
- for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++)
- {
- drawOtherText(canvas, i, 1);
- }
- }
- /**
- * @param canvas
- * @param position
- * 距离mCurrentSelected的差值
- * @param type
- * 1表示向下绘制,-1表示向上绘制
- */
- private void drawOtherText(Canvas canvas, int position, int type)
- {
- float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
- * mMoveLen);
- float scale = parabola(mViewHeight / 4.0f, d);
- float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
- mPaint.setTextSize(size);
- mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
- float y = (float) (mViewHeight / 2.0 + type * d);
- FontMetricsInt fmi = mPaint.getFontMetricsInt();
- float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));
- canvas.drawText(mDataList.get(mCurrentSelected + type * position),
- (float) (mViewWidth / 2.0), baseline, mPaint);
- }
- /**
- * 抛物线
- *
- * @param zero
- * 零点坐标
- * @param x
- * 偏移量
- * @return scale
- */
- private float parabola(float zero, float x)
- {
- float f = (float) (1 - Math.pow(x / zero, 2));
- return f < 0 ? 0 : f;
- }
- @Override
- public boolean onTouchEvent(MotionEvent event)
- {
- switch (event.getActionMasked())
- {
- case MotionEvent.ACTION_DOWN:
- doDown(event);
- break;
- case MotionEvent.ACTION_MOVE:
- doMove(event);
- break;
- case MotionEvent.ACTION_UP:
- doUp(event);
- break;
- }
- return true;
- }
- private void doDown(MotionEvent event)
- {
- if (mTask != null)
- {
- mTask.cancel();
- mTask = null;
- }
- mLastDownY = event.getY();
- }
- private void doMove(MotionEvent event)
- {
- mMoveLen += (event.getY() - mLastDownY);
- if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2)
- {
- // 往下滑超过离开距离
- moveTailToHead();
- mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
- } else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2)
- {
- // 往上滑超过离开距离
- moveHeadToTail();
- mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
- }
- mLastDownY = event.getY();
- invalidate();
- }
- private void doUp(MotionEvent event)
- {
- // 抬起手后mCurrentSelected的位置由当前位置move到中间选中位置
- if (Math.abs(mMoveLen) < 0.0001)
- {
- mMoveLen = 0;
- return;
- }
- if (mTask != null)
- {
- mTask.cancel();
- mTask = null;
- }
- mTask = new MyTimerTask(updateHandler);
- timer.schedule(mTask, 0, 10);
- }
- class MyTimerTask extends TimerTask
- {
- Handler handler;
- public MyTimerTask(Handler handler)
- {
- this.handler = handler;
- }
- @Override
- public void run()
- {
- handler.sendMessage(handler.obtainMessage());
- }
- }
- public interface onSelectListener
- {
- void onSelect(String text);
- }
- }
代码里的注释都写的很清楚了。接下来,我们就用写好的PickerView实现文章开头的图片效果吧~
首先看MainActivity的布局:
[html] view plain copy
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#000000" >
- <RelativeLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:background="#ffffff" >
- <com.jingchen.timerpicker.PickerView
- android:id="@+id/minute_pv"
- android:layout_width="80dp"
- android:layout_height="160dp" />
- <TextView
- android:id="@+id/minute_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:layout_toRightOf="@id/minute_pv"
- android:text="分"
- android:textColor="#ffaa33"
- android:textSize="26sp"
- android:textStyle="bold" />
- <com.jingchen.timerpicker.PickerView
- android:id="@+id/second_pv"
- android:layout_width="80dp"
- android:layout_height="160dp"
- android:layout_toRightOf="@id/minute_tv" />
- <TextView
- android:id="@+id/second_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:layout_toRightOf="@id/second_pv"
- android:text="秒"
- android:textColor="#ffaa33"
- android:textSize="26sp"
- android:textStyle="bold" />
- </RelativeLayout>
- </RelativeLayout>
两个PickerView两个TextView,很简单。
下面是MainActivity的代码:
[java] view plain copy
- package com.jingchen.timerpicker;
- import java.util.ArrayList;
- import java.util.List;
- import com.jingchen.timerpicker.PickerView.onSelectListener;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity
- {
- PickerView minute_pv;
- PickerView second_pv;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- minute_pv = (PickerView) findViewById(R.id.minute_pv);
- second_pv = (PickerView) findViewById(R.id.second_pv);
- List<String> data = new ArrayList<String>();
- List<String> seconds = new ArrayList<String>();
- for (int i = 0; i < 10; i++)
- {
- data.add("0" + i);
- }
- for (int i = 0; i < 60; i++)
- {
- seconds.add(i < 10 ? "0" + i : "" + i);
- }
- minute_pv.setData(data);
- minute_pv.setOnSelectListener(new onSelectListener()
- {
- @Override
- public void onSelect(String text)
- {
- Toast.makeText(MainActivity.this, "选择了 " + text + " 分",
- Toast.LENGTH_SHORT).show();
- }
- });
- second_pv.setData(seconds);
- second_pv.setOnSelectListener(new onSelectListener()
- {
- @Override
- public void onSelect(String text)
- {
- Toast.makeText(MainActivity.this, "选择了 " + text + " 秒",
- Toast.LENGTH_SHORT).show();
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu)
- {
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }
OK了,自定义自己的TimerPicker就是这么简单~
来源:http://blog.csdn.net/zhongkejingwang/article/details/38513301