Canvas - zooming in, shifting, and scaling on Android

前端 未结 5 985
广开言路
广开言路 2020-12-24 00:34

I\'m currently implementing a draw function on a webview image (the elephant below). I don\'t have a problem drawing on it but the zoom function does some funky stuff (2nd i

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 01:18

    A good way to accomplish all the different effects you are trying to do in a very simple manner is making use of the canvas method

    canvas.drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint);

    This method allow you, to take the whole source bitmap or just a small sample of it (Rect src), and project it as you wish (Rect dst) doing the scaling / translation of matrix calculations automatically for you as shown in the example below:

    This example just scales / zooms the whole image...

         Canvas canvas = null;
         Bitmap elephantBmp = null;
         Rect src = new Rect();
         Rect postRect = new Rect();
         Paint paintIfAny = new Paint();
    
         //To scale the whole image, first take the whole source and then postRect with a bigger size... 
         src.top = src.left = 0;
         src.right = elephantBmp.getWidth();
         src.bottom = elephantBmp.getHeight();
         //Here you have the chance to translate / scale the image(in this case i will not translate it but just scale it...)
         postRect.top = postRect.left = 0;
         postRect.right = (int)(elephantBmp.getWidth() * 1.1F);
         postRect.bottom = (int)(elephantBmp.getHeight() * 1.1F);
    
         canvas.drawBitmap(elephantBmp, src, postRect, paintIfAny);
    

    And this example takes just a sample of the image and shows it "inner zoom effect"

         Canvas canvas = null;
         Bitmap elephantBmp = null;
         Rect src = new Rect();
         Rect postRect = new Rect();
         Paint paintIfAny = new Paint();
    
        //To shift the whole image, first take the part of the original source image you want to show 
         src.top = topPosition;//Top coordinate of piece of image to show
         src.left = leftPosition;//Left coordinate of piece of image to show
         src.right = rightPosition;//Right coordinate of piece of image to show
         src.bottom = bottomPosition;//Bottom coordinate of piece of image to show
         //Here you have the chance to show it as big as you want...
         postRect.top = postRect.left = 0;
         postRect.right = (int)(src.width() * 1.1F);
         postRect.bottom = (int)(src.height() * 1.1F);
    
         canvas.drawBitmap(elephantBmp, src, postRect, paintIfAny);
    

    By making use of these src/dst objects you can do pretty much any effect you want on android, is a simple and really powerful tool

    Hope this helps.

    Regards!

提交回复
热议问题