概述
我相信很多用过英语应用的同学都看多一个放大镜的效果,就是选中一段文字后,会有一个放大镜,这个究竟怎么实现的呢,我们今天来分析分析。
源码分析
- public class ShaderView extends View {
- private final Bitmap bitmap;
- private final ShapeDrawable drawable;
- // 放大镜的半径
- private static final int RADIUS = 80;
- // 放大倍数
- private static final int FACTOR = 3;
- private final Matrix matrix = new Matrix();
- public ShaderView(Context context) {
- super(context);
- Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.demo);
- bitmap = bmp;
- BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(bmp,
- bmp.getWidth() * FACTOR, bmp.getHeight() * FACTOR, true), TileMode.CLAMP, TileMode.CLAMP);
- // 圆形的drawable
- drawable = new ShapeDrawable(new OvalShape());
- drawable.getPaint().setShader(shader);
- drawable.setBounds(0, 0, RADIUS * 2, RADIUS * 2);
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- final int x = (int) event.getX();
- final int y = (int) event.getY();
- // 这个位置表示的是,画shader的起始位置
- matrix.setTranslate(RADIUS - x * FACTOR, RADIUS - y * FACTOR);
- drawable.getPaint().getShader().setLocalMatrix(matrix);
- // bounds,就是那个圆的外切矩形
- drawable.setBounds(x - RADIUS, y - RADIUS, x + RADIUS, y + RADIUS);
- invalidate();
- return true;
- }
- @Override
- public void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- canvas.drawBitmap(bitmap, 0, 0, null);
- drawable.draw(canvas);
- }
- }
基本原理就是使用ShapeDrawable构造一个圆形的drawable,然后它的paint的shader设置为将要放大的图片,然后就是简单的位置移动问题了。放大镜的半径和放大倍数都可以在代码里面修改,代码都有注释,应该很好理解了。
不过,一个问题如果只有一种解决方法的话,那未免有点令人沮丧,想玩点另类的都不行。玩程序就得玩出个性,玩出激情。哈哈,废话太多,切回正题。再来看看放大镜的另外一种实现吧
- public class PathView extends View {
- private final Path mPath = new Path();
- private final Matrix matrix = new Matrix();
- private final Bitmap bitmap;
- // 放大镜的半径
- private static final int RADIUS = 80;
- // 放大倍数
- private static final int FACTOR = 2;
- private int mCurrentX, mCurrentY;
- public PathView(Context context) {
- super(context);
- mPath.addCircle(RADIUS, RADIUS, RADIUS, Direction.CW);
- matrix.setScale(FACTOR, FACTOR);
- bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.demo);
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- mCurrentX = (int) event.getX();
- mCurrentY = (int) event.getY();
- invalidate();
- return true;
- }
- @Override
- public void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- // 底图
- canvas.drawBitmap(bitmap, 0, 0, null);
- // 剪切
- canvas.translate(mCurrentX - RADIUS, mCurrentY - RADIUS);
- canvas.clipPath(mPath);
- // 画放大后的图
- canvas.translate(RADIUS - mCurrentX * FACTOR, RADIUS - mCurrentY * FACTOR);
- canvas.drawBitmap(bitmap, matrix, null);
- }
- }
这里使用的是Path类,将canvas剪切出一块圆形区域,在其上绘制放大的部分。
本文作者:佚名
来源:51CTO