您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Android中怎么實(shí)現(xiàn)放大鏡效果,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
源碼分析
public class ShaderView extends View { private final Bitmap bitmap; private final ShapeDrawable drawable; // 放大鏡的半徑 private static final int RADIUS = 80; // 放大倍數(shù) 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(); // 這個(gè)位置表示的是,畫shader的起始位置 matrix.setTranslate(RADIUS - x * FACTOR, RADIUS - y * FACTOR); drawable.getPaint().getShader().setLocalMatrix(matrix); // bounds,就是那個(gè)圓的外切矩形 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構(gòu)造一個(gè)圓形的drawable,然后它的paint的shader設(shè)置為將要放大的圖片,然后就是簡單的位置移動(dòng)問題了。放大鏡的半徑和放大倍數(shù)都可以在代碼里面修改,代碼都有注釋,應(yīng)該很好理解了。
不過,一個(gè)問題如果只有一種解決方法的話,那未免有點(diǎn)令人沮喪,想玩點(diǎn)另類的都不行。玩程序就得玩出個(gè)性,玩出激情。哈哈,廢話太多,切回正題。再來看看放大鏡的另外一種實(shí)現(xiàn)吧
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; // 放大倍數(shù) 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); } }
上述就是小編為大家分享的Android中怎么實(shí)現(xiàn)放大鏡效果了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。