为了实现毛玻璃效果,我们需要一组compute kernels(.rs文件中编写),及一组用于控制renderscript相关的javaapi(.rs文件自动生成为java类)。 由于compute kernels的编写需要一定的学习成本,从jelly_bean_mr1开始,androied内置了一些compute kernels用于常用的操作,其中就包括了gaussian blur。
下面,通过实操来讲解一下renderscript来实现高斯模糊,最终实现效果(讲文字背景进行模糊处理):
实现代码:
<html><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><textarea style="width:99%;height:99%">private void applyblur() { image.getviewtreeobserver().addonpredrawlistener(new viewtreeobserver.onpredrawlistener() { @override public boolean onpredraw() { image.getviewtreeobserver().removeonpredrawlistener(this); image.builddrawingcache(); bitmap bmp = image.getdrawingcache(); blur(bmp, text, true); return true; } }); } @targetapi(build.version_codes.jelly_bean_mr1) private void blur(bitmap bkg, view view) { long startms = system.currenttimemillis(); float radius = 20; bitmap overlay = bitmap.createbitmap((int)(view.getmeasuredwidth()), (int)(view.getmeasuredheight()), bitmap.config.argb_8888); canvas canvas = new canvas(overlay); canvas.translate(-view.getleft(), -view.gettop()); canvas.drawbitmap(bkg, 0, 0, null); renderscript rs = renderscript.create(secondactivity.this); allocation overlayalloc = allocation.createfrombitmap(rs, overlay); scriptintrinsicblur blur = scriptintrinsicblur.create(rs, overlayalloc.getelement()); blur.setinput(overlayalloc); blur.setradius(radius); blur.foreach(overlayalloc); overlayalloc.copyto(overlay); view.setbackground(new bitmapdrawable(getresources(), overlay)); rs.destroy(); statustext.settext("cost " + (system.currenttimemillis() - startms) + "ms"); }</textarea></body></html>
布局如下:
<?xml version="1.0" encoding="utf-8"?> <framelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <imageview android:id="@+id/picture" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/splash" android:scaletype="centercrop" /> <textview android:id="@+id/text" android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="gaussian blur" android:textcolor="@android:color/black" android:layout_gravity="center_vertical" android:textstyle="bold" android:textsize="48sp" /> <linearlayout android:id="@+id/controls" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#7f000000" android:orientation="vertical" android:layout_gravity="bottom" /> </framelayout>
以上所述是小编给大家介绍的android中实现ios中的毛玻璃效果,希望对大家有所帮助
如对本文有疑问, 点击进行留言回复!!
android -- ndk (stack corruption detected)
Android Span富文本图文混排 - ImageSpan(图文垂直居中)
Element DateTimePicker日期时间选择器的使用示例
【Appium踩坑】小米手机,启动报错:exited with code 255 writing to settings requires:android.permission.WRITE_SECUR
android 拍照 预览图与 照片分辨率(可视区域)不一致
[PAT顶级]1025 Keep at Most 100 Characters (35分)
网友评论