Android中实现倒影效果

Linux大全评论1.2K views阅读模式

Android中实现原理

实现倒影可以使用 OpenGL 等 3D 接口方法,也可以用 2D 的方法模拟。

用 2D 方法实现倒影需要从两个方面考虑:

倒影是上、下翻转的图像;

从上到下透明度越来越大。

图像翻转

原理上讲,图像的翻转实际就是将图像数据上下行互换。

透明度渐变

实现透明度渐变有两种方法,一是使用蒙板;二是直接修改像素数据,修改每个像素的 alpha 值。

对于蒙板法,事先做好一张透明度渐变的图,这就是我们的蒙板,在绘制完图像之后把蒙板图片绘制上去,这样就产生了透明度渐变的效果。

对于第二种方法,我们需要首先读出图片的数据,然后修改每个像素的 alpha 值。逐行增加 alpha 值,产生的效果是自上向下由暗变亮。

 1 
 2     /**
 3      * get reflection bitmap of the original bitmap.
 4      * @param srcBitmap
 5      * @return
 6      */
 7     private Bitmap makeReflectionBitmap(Bitmap srcBitmap){
 8         int bmpWidth = srcBitmap.getWidth();
 9         int bmpHeight = srcBitmap.getHeight();
10         int[] pixels = new int[bmpWidth * bmpHeight * 4];
11         srcBitmap.getPixels(pixels, 0, bmpWidth, 00, bmpWidth, bmpHeight);
12 
13         //get reversed bitmap
14         Bitmap reverseBitmap = Bitmap.createBitmap(bmpWidth, bmpHeight,
15                 Bitmap.Config.ARGB_8888);
16         for (int y = 0; y < bmpHeight; y++) {
17             reverseBitmap.setPixels(pixels, y * bmpWidth, bmpWidth, 0,
18                     bmpHeight - y - 1, bmpWidth, 1);
19         }
20         
21         //get reflection bitmap based on the reversed one
22         reverseBitmap.getPixels(pixels, 0, bmpWidth, 00, bmpWidth, bmpHeight);
23         Bitmap reflectionBitmap = Bitmap.createBitmap(bmpWidth, bmpHeight,
24                 Bitmap.Config.ARGB_8888);
25         int alpha = 0x00000000;
26         for (int y = 0; y < bmpHeight; y++) {
27             for (int x = 0; x < bmpWidth; x++) {
28                 int index = y * bmpWidth + x;
29                 int r = (pixels[index] >> 16& 0xff;
30                 int g = (pixels[index] >> 8& 0xff;
31                 int b = pixels[index] & 0xff;
32 
33                 pixels[index] = alpha | (r << 16| (g << 8| b;
34                 
35                 reflectionBitmap.setPixel(x, y, pixels[index]);
36             }
37             alpha = alpha + 0x01000000;
38         }
39         
40         return reflectionBitmap;
41     }

企鹅博客
  • 本文由 发表于 2020年7月12日 07:27:07
  • 转载请务必保留本文链接:https://www.qieseo.com/148395.html

发表评论