一行代码实现高斯模糊

前言:有一个音乐播放器的项目,背景需要根据歌曲的封面进行模糊展示,搜罗了很久,找到一个不错的解决方案,不需要我们进行NDK的开发,android帮我们在framework实现好了借鉴

/**
     * 模糊图片
     * @param bitmap 原图片
     * @param radius 模糊度  0~25
     * @param context
     * @return 模糊后的图片
     */
    public static Bitmap blurBitmap(Bitmap bitmap, float radius, Context context) {
    //Create renderscript
    RenderScript rs = RenderScript.create(context);
 
    //Create allocation from Bitmap
    Allocation allocation = Allocation.createFromBitmap(rs, bitmap);
    
    Type t = allocation.getType();
 
    //Create allocation with the same type
    Allocation blurredAllocation = Allocation.createTyped(rs, t);
 
    //Create script
    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    //Set blur radius (maximum 25.0)
    blurScript.setRadius(radius);
    //Set input for script
    blurScript.setInput(allocation);
    //Call script for output allocation
    blurScript.forEach(blurredAllocation);
 
    //Copy script result into bitmap
    blurredAllocation.copyTo(bitmap);
 
    //Destroy everything to free memory
    allocation.destroy();
    blurredAllocation.destroy();
    blurScript.destroy();
    t.destroy();
    rs.destroy();
    return bitmap;
}

感谢android,感谢开源

上一篇:转 OC之iOS开发常用Unix指令


下一篇:iOS夯实:ARC时代的内存管理