Android RenderScript 简单高效实现图片的高斯模糊效果

本文介绍如何使用Android的RenderScript实现高斯模糊效果,并提供了一段简洁高效的代码示例。文章还介绍了如何设置模糊半径以调整图片清晰度,以及如何在不同Android版本间保持兼容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高斯模糊(Gaussian blur)和毛玻璃效果(亦称磨砂效果),近两年在移动端的UI设计上越来越流行,特别是iOS手机上出现的较多,iOS系统也提供了相应的API帮助开发人员分分钟实现这两个效果。而Android系统则经历了一个漫长的探索过程,对图片的处理,从Java算法到NDK方式实现等,各种摸索层出不穷。

值得欣慰的是,Google终于在API 11中引入了RenderScript,一个强大的图片处理框架,帮助Android开发人员专注于图片处理算法而不是API的调度工作。使用RenderScript进行图片处理,还需要了解RenderScript Intrinsics,一些可以帮助RenderScript快速实现各种图片处理的操作类。比如ScriptIntrinsicBlur,可以简单高效地帮助我们实现高斯模糊效果:

public Bitmap blurBitmap(Bitmap bitmap){

    //Let's create an empty bitmap with the same size of the bitmap we want to blur
    Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);

    //Instantiate a new Renderscript
    RenderScript rs = RenderScript.create(getApplicationContext());

    //Create an Intrinsic Blur Script using the Renderscript
    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

    //Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
    Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
    Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);

    //Set the radius of the blur: 0 < radius <= 25
    blurScript.setRadius(25.0f);

    //Perform the Renderscript
    blurScript.setInput(allIn);
    blurScript.forEach(allOut);

    //Copy the final bitmap created by the out Allocation to the outBitmap
    allOut.copyTo(outBitmap);

    //recycle the original bitmap
    bitmap.recycle();

    //After finishing everything, we destroy the Renderscript.
    rs.destroy();

    return outBitmap;   

}

通过设置模糊半径(radius)的大小来控制图片的清晰度,简短的几行代码轻松实现图片的高斯模糊处理,我们看一下radius等于最大值25时的图片模糊效果:

原图效果:


RenderScript-Blur-Before

高斯模糊:


RenderScript-Blur-After

注意:ScriptIntrinsicBlur的相关方法只支持API 17及以上版本的系统,为了兼容旧版本,Google供了support.v8包,在使用RenderScript和Intrinsics类时,引入v8包中的相关类即可:

import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;

同时,在app/build.gradle文件的defaultConfig配置中,添加如下两行内容即可:

defaultConfig {
    ......
    renderscriptTargetApi 19
    renderscriptSupportModeEnabled  true
}

在设计上巧妙地运用高斯模糊往往能达到出乎意料的体验效果,比如大神daimajia就利用RenderScript和NineOldAndroids做了一个比较有创意的UI交互,开源库为:AndroidViewHover,效果如下,感兴趣的同学可以一探究竟:

daimajia-AndroidViewHover.gif

关于Android平台的图片模糊处理,在GitHub上有一些较为优秀的开源类库,笔者整理了一些,推荐给大家学习使用:


转自: https://www.jianshu.com/p/b262b6ad3456
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值