每日记录一点点,收获一点点
首先先看效果图
思路:自定义一个控件继承View,然后将两张图片加载进去,根据屏幕宽高和两张图片的宽高设置好位置,然后设置监听点击事件和移动事件,最后对点击的位置和移动的位置进行判断,接下来我们跟着代码一步一步实现。末尾有完整代码。
第一步:
自定义一个SlideLockView,继承View,重写View三个方法,然后再init()方法中通过BitmapFactory创建bitmap对象(两张图片),再获取图片的宽高值。
代码如下:
public class SlideLockView extends View {
private Bitmap hand;
private Bitmap lock;
private int handWidth;
private int lockWidth;
private int handHeight;
public SlideLockView(Context context) {
this(context, null);
init();
}
public SlideLockView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init();
}
public SlideLockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
hand = BitmapFactory.decodeResource(getResources(), R.drawable.icon_hand);
lock = BitmapFactory.decodeResource(getResources(), R.drawable.icon_lock);
handWidth = hand.getWidth();
lockWidth = lock.getWidth();
handHeight = hand.getHeight();
}
}
第二步:
重写onDraw()方法,在方法中画出两张图片
private int left;
private int top;
private int currentX;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
left = getMeasuredWidth() / 2 - lockWidth / 2;
top = getMeasuredHeight() / 2 - handWidth / 2;
//滑块的左上角X轴坐标
currentX = left;
canvas.drawBitmap(lock, left, top, null);
canvas.drawBitmap(hand, currentX, top, null);
}
在使用drawBitmap方法时,需要传入几个参数
1.bit