Android使用API实现图像扭曲效果示例
本文实例讲述了Android使用API实现图像扭曲效果。分享给大家供大家参考,具体如下:
/** *AndroidAPI实现图像扭曲效果 *@description: *@date2016-7-22下午2:19:12 */ publicclassBitmapMeshextendsGraphicsActivity{ @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(newSampleView(this)); } privatestaticclassSampleViewextendsView{ //定义常量,指定该图片横向被划分为20格 privatestaticfinalintWIDTH=20; //定义常量,指定该图片纵向上被划分为20格 privatestaticfinalintHEIGHT=20; //记录该图像上包含441个顶点 privatestaticfinalintCOUNT=(WIDTH+1)*(HEIGHT+1); //位图 privatefinalBitmapmBitmap; //数组,记录Bitmap上的21*21个点的坐标 privatefinalfloat[]mVerts=newfloat[COUNT*2]; //记录Bitmap上的21*21个点经过扭曲后的坐标 privatefinalfloat[]mOrig=newfloat[COUNT*2]; privatefinalMatrixmMatrix=newMatrix(); privatefinalMatrixmInverse=newMatrix(); privatestaticvoidsetXY(float[]array,intindex,floatx,floaty){ array[index*2+0]=x; array[index*2+1]=y; } publicSampleView(Contextcontext){ super(context); setFocusable(true); //加载图片 mBitmap=BitmapFactory.decodeResource(getResources(),R.raw.beach); //获取图像的宽度和高度 floatw=mBitmap.getWidth(); floath=mBitmap.getHeight(); //构建扭曲数据 intindex=0; for(inty=0;y<=HEIGHT;y++){ floatfy=h*y/HEIGHT; for(intx=0;x<=WIDTH;x++){ floatfx=w*x/WIDTH; //初始化orig,verts数组 //初始化,orig,verts两个数组均匀地保存了21*21个点的x,y坐标 setXY(mVerts,index,fx,fy); setXY(mOrig,index,fx,fy); index+=1; } } //设置平移效果 mMatrix.setTranslate(10,10); //实现乱矩阵逆向坐标映射 mMatrix.invert(mInverse); } @Override protectedvoidonDraw(Canvascanvas){ canvas.drawColor(0xFFCCCCCC); //对matrix的变换应用到canvas上的所有对象. canvas.concat(mMatrix); /** *bitmap需要扭曲的源位图 *meshWidth控制在横向上把该源位图划成成多少格 *meshHeight控制在纵向上把该源位图划成成多少格 *verts长度为(meshWidth+1)*(meshHeight+1)*2的数组,它记录了扭曲后的位图各顶点位置 *vertOffset控制verts数组中从第几个数组元素开始才对bitmap进行扭曲 */ canvas.drawBitmapMesh(mBitmap,WIDTH,HEIGHT,mVerts,0,null,0, null); } //根据触摸事件的位置计算verts数组里各元素的值 privatevoidwarp(floatcx,floatcy){ finalfloatK=10000; float[]src=mOrig; float[]dst=mVerts; for(inti=0;i=1){ dst[i+0]=cx; dst[i+1]=cy; }else{ //控制各顶点向触摸事件发生点偏移 dst[i+0]=x+dx*pull; dst[i+1]=y+dy*pull; } } } privateintmLastWarpX=-9999;//don'tmatchatouchcoordinate privateintmLastWarpY; @SuppressLint("ClickableViewAccessibility")@Override publicbooleanonTouchEvent(MotionEventevent){ float[]pt={event.getX(),event.getY()}; //用当前矩阵改变pts中的值,然后存储在pts中,同上,pts也是存储点的坐标的数组 mInverse.mapPoints(pt); intx=(int)pt[0]; inty=(int)pt[1]; if(mLastWarpX!=x||mLastWarpY!=y){ mLastWarpX=x; mLastWarpY=y; warp(pt[0],pt[1]); invalidate(); } returntrue; } } }
另:关于AndroidMatrix可参考:https://www.nhooo.com/article/121048.htm
希望本文所述对大家Android程序设计有所帮助。