zoukankan      html  css  js  c++  java
  • 教你一分钟实现动态模糊效果

    现在,越来越多的App里面使用了模糊效果,我尤其喜欢雅虎天气的界面,上滑的时候背景图片会跟着移动,最重要的是背景图片会根据手指上下移动的距离来进行不同程度的模糊,感觉甚为惊奇,毕竟大家都知道,在Android平台上进行模糊渲染是一个相当耗CPU也相当耗时的操作,一旦处理不好,卡顿是在所难免的。虽然我并不知道雅虎天气是怎么做出这种效果的,但是简单的模仿一下的话,还是能做到的。

    一般来说,考虑到效率,渲染一张图片最好的方法是使用OpenGL,其次是使用C/C++,使用Java代码是最慢的。但是Android推出RenderScript之后,我们就有了新的选择,测试表明,使用RenderScript的渲染效率和使用C/C++不相上下,但是使用RenderScript却比使用JNI简单地多!同时,Android团队提供了RenderScript的支持库,使得在低版本的Android平台上也能使用。

    不过在使用RenderScript之前,对于模糊一张图片,需要注意的是,我们应该尽量不要使用原尺寸分辨率的图片,最好将图片缩小比例,这小渲染的效率要高一些。

    动态模糊的实现

    如何使用RenderScript来模糊一张图片呢?废话不多说,先上核心代码:

     1 public class BlurBitmap {
     2     /**
     3      * 图片缩放比例
     4      */
     5     private static final float BITMAP_SCALE = 0.4f;
     6     /**
     7      * 最大模糊度(在0.0到25.0之间)
     8      */
     9     private static final float BLUR_RADIUS = 25f;
    10 
    11     /**
    12      * 模糊图片的具体方法
    13      *
    14      * @param context   上下文对象
    15      * @param image     需要模糊的图片
    16      * @return          模糊处理后的图片
    17      */
    18     public static Bitmap blur(Context context, Bitmap image) {
    19         // 计算图片缩小后的长宽
    20         int width = Math.round(image.getWidth() * BITMAP_SCALE);
    21         int height = Math.round(image.getHeight() * BITMAP_SCALE);
    22 
    23         // 将缩小后的图片做为预渲染的图片。
    24         Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
    25         // 创建一张渲染后的输出图片。
    26         Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
    27 
    28         // 创建RenderScript内核对象
    29         RenderScript rs = RenderScript.create(context);
    30         // 创建一个模糊效果的RenderScript的工具对象
    31         ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    32 
    33         // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。
    34         // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。
    35         Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    36         Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    37 
    38         // 设置渲染的模糊程度, 25f是最大模糊度
    39         blurScript.setRadius(BLUR_RADIUS);
    40         // 设置blurScript对象的输入内存
    41         blurScript.setInput(tmpIn);
    42         // 将输出数据保存到输出内存中
    43         blurScript.forEach(tmpOut);
    44 
    45         // 将数据填充到Allocation中
    46         tmpOut.copyTo(outputBitmap);
    47 
    48         return outputBitmap;
    49     }
    50 }

    完成上面的代码后,需要在app的gradle文件中添加如下的支持:

    1  defaultConfig {
    2     ......
    3     renderscriptTargetApi 19
    4     renderscriptSupportModeEnabled true
    5 }

    代码做了简单的注释以帮助理解,如果需要详细了解,可以查阅官方文档:RenderScript

    然后,我们可以看一下模糊前和模糊后的效果对比:

    将图片模糊后,接下来要考虑的是怎么实现动态模糊效,有一点需要注意的是,即使我们使用了RenderScript这种高效的渲染方式,但是在实际测试中,渲染一张500*700分辨率的PNG格式图片,在我的Pro 6手机上,仍然需要50ms左右的时间(渲染最大模糊度的情况下),显然如果使用上面的代码进行实时渲染的话,会造成界面严重的卡顿。

    既然实时渲染这条路走不通,那么就需要我们另辟蹊径了,我这里可以提供一种方法:先将图片进行最大程度的模糊处理,再将原图放置在模糊后的图片上面,通过不断改变原图的透明度(Alpha值)来实现动态模糊效果。

    简单的代码如下:

     1 public class MainActivity extends AppCompatActivity {
     2 
     3     /**
     4      * 原始图片控件
     5      */
     6     private ImageView mOriginImg;
     7 
     8     /**
     9      * 模糊后的图片控件
    10      */
    11     private ImageView mBluredImage;
    12 
    13     /**
    14      * 进度条SeekBar
    15      */
    16     private SeekBar mSeekBar;
    17 
    18     /**
    19      * 显示进度的文字
    20      */
    21     private TextView mProgressTv;
    22 
    23     /**
    24      * 透明度
    25      */
    26     private int mAlpha;
    27 
    28     /**
    29      * 原始图片
    30      */
    31     private Bitmap mTempBitmap;
    32 
    33     /**
    34      * 模糊后的图片
    35      */
    36     private Bitmap mFinalBitmap;
    37 
    38     @Override
    39     protected void onCreate(Bundle savedInstanceState) {
    40         super.onCreate(savedInstanceState);
    41         setContentView(R.layout.activity_main);
    42 
    43         // 初始化视图
    44         initViews();
    45 
    46         // 获取图片
    47         mTempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dayu);
    48         mFinalBitmap = BlurBitmap.blur(this, mTempBitmap);
    49 
    50         // 填充模糊后的图像和原图
    51         mBluredImage.setImageBitmap(mFinalBitmap);
    52         mOriginImg.setImageBitmap(mTempBitmap);
    53 
    54         // 处理seekbar滑动事件
    55         setSeekBar();
    56     }
    57 
    58     /**
    59      * 初始化视图
    60      */
    61     private void initViews() {
    62         mBluredImage = (ImageView) findViewById(R.id.activity_main_blured_img);
    63         mOriginImg = (ImageView) findViewById(R.id.activity_main_origin_img);
    64         mSeekBar = (SeekBar) findViewById(R.id.activity_main_seekbar);
    65         mProgressTv = (TextView) findViewById(R.id.activity_main_progress_tv);
    66     }
    67 
    68     /**
    69      * 处理seekbar滑动事件
    70      */
    71     private void setSeekBar() {
    72         mSeekBar.setMax(100);
    73         mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    74             @Override
    75             public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    76                 mAlpha = progress;
    77                 mOriginImg.setAlpha((int) (255 - mAlpha * 2.55));
    78                 mProgressTv.setText(String.valueOf(mAlpha));
    79             }
    80 
    81             @Override
    82             public void onStartTrackingTouch(SeekBar seekBar) {
    83 
    84             }
    85 
    86             @Override
    87             public void onStopTrackingTouch(SeekBar seekBar) {
    88 
    89             }
    90         });
    91     }
    92 }

    xml布局文件代码如下:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout
     3     xmlns:android="http://schemas.android.com/apk/res/android"
     4     android:orientation="vertical"
     5     android:id="@+id/activity_main"
     6     android:layout_width="match_parent"
     7     android:layout_height="match_parent">
     8 
     9     <FrameLayout
    10         android:layout_width="match_parent"
    11         android:layout_weight="1"
    12         android:layout_height="0dp">
    13 
    14         <ImageView
    15             android:id="@+id/activity_main_blured_img"
    16             android:scaleType="centerCrop"
    17             android:src="@drawable/dayu"
    18             android:layout_width="match_parent"
    19             android:layout_height="match_parent"/>
    20 
    21         <ImageView
    22             android:id="@+id/activity_main_origin_img"
    23             android:scaleType="centerCrop"
    24             android:layout_width="match_parent"
    25             android:layout_height="match_parent"/>
    26     </FrameLayout>
    27 
    28     <LinearLayout
    29         android:orientation="vertical"
    30         android:layout_width="match_parent"
    31         android:layout_height="80dp">
    32 
    33         <SeekBar
    34             android:layout_marginTop="@dimen/activity_vertical_margin"
    35             android:id="@+id/activity_main_seekbar"
    36             android:layout_width="match_parent"
    37             android:layout_height="wrap_content"
    38             android:layout_marginLeft="16dp"
    39             android:layout_marginRight="16dp"/>
    40 
    41         <TextView
    42             android:id="@+id/activity_main_progress_tv"
    43             android:text="0"
    44             android:textSize="24sp"
    45             android:layout_gravity="center"
    46             android:layout_width="wrap_content"
    47             android:layout_height="wrap_content"/>
    48     </LinearLayout>
    49 
    50 </LinearLayout>

    效果如下:

    怎么样?是不是很简单的样子?只需要调用模糊处理方法,并在SeekBar的滑动监听里面调用原图像的setAlpha()方法,来实现动态模糊效果。

    你以为这样就完了?不不不,我们的目的并不是这么单纯,哦,不对,并不是这么简单。还记得文章开头的时候说了吗?我们的终极目的是要简单地模仿一下雅虎天气的界面效果。

    仿雅虎天气界面

    有了上面的基础,就可以很容易地模仿雅虎天气的界面效果。简单来说,在上面制作出的效果基础上,有以下两点需要注意的地方:

    • 需要要监听滑动事件,然后再将背景图片调用setTop()方法,将图片向上平移一段距离。
    • 要向上平移图片,还需要手动增加图片的高度,不然图片向上平移后,底部就会有留白。设置图片高度的核心代码如下:
     1 WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
     2 Display display = wm.getDefaultDisplay();
     3 Point point = new Point();
     4 display.getSize(point);
     5 // 获取到ImageView的高度
     6 int height = point.y;
     7 ViewGroup.LayoutParams params = imageView.getLayoutParams();
     8 params.width = ViewGroup.LayoutParams.MATCH_PARENT;
     9 // 将ImageView的高度增加100
    10 params.height = height + 100;
    11 // 应用更改设置
    12 imageView.requestLayout();

    完成上面两点的内容后,基本就可以模仿出雅虎天气的首页了。

    结合第一个例子的demo,效果如下:

     

  • 相关阅读:
    LeetCode——230. 二叉搜索树中第K小的元素
    LeetCode——456.132模式
    LeetCode——623.在二叉树中增加一行
    LeetCode——735.行星碰撞
    翻译——2_Linear Regression and Support Vector Regression
    LeetCode——919.完全二叉树插入器
    论文翻译——Deep contextualized word representations
    LeetCode——853.车队
    Leetcode——863.二叉树中所有距离为 K 的结点
    Pytorch——BERT 预训练模型及文本分类
  • 原文地址:https://www.cnblogs.com/huolongluo/p/6412575.html
Copyright © 2011-2022 走看看