您的位置:首页 > 移动开发 > Android开发

Android学习------使用RenderScript ,ScriptIntrinsicBlur实现高斯模糊

2017-04-17 10:49 393 查看
android新增了android.support.v8.renderscript支持库,提供了高斯模糊的实现。

参考自:

https://developer.android.google.cn/guide/topics/renderscript/compute.html#using-rs-from-java

http://stackoverflow.com/questions/2067955/fast-bitmap-blur-for-android-sdk

Setup 1

在你的build.gradle中添加

defaultConfig {
(...)

renderscriptTargetApi 18
renderscriptSupportModeEnabled true

(...)
}


Java code

public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private ImageView img;
private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap blurTemplate = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, options);
RenderScript rs = RenderScript.create(MainActivity.this);
final Allocation input = Allocation.createFromBitmap(rs, blurTemplate);
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(blurTemplate);
img.setImageBitmap(blurTemplate);

}
});

}
}


注意在解码图片的时候可能会发生OOM

xml code

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<ImageView
android:id="@+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@mipmap/ic_launcher"
/>

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/img"
android:text="start bulr"
android:textAllCaps="false"
/>
</RelativeLayout>


demo演示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: