How to use IconCompat.createWithAdaptiveBitmap - android

I want to apply adaptive icons to shortcuts generated by following code (code is only for reference, it does not compile):
ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, "com.myapp.mainactivity")
.setShortLabel(context.getResources().getString("short label"))
.setLongLabel(context.getResources().getString("long label"))
.setIcon(IconCompat.createWithAdaptiveBitmap(bitmap)
.setIntent(targetActivityIntent)
.build();
public Bitmap getLauncherIcon(final Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return null;
} else {
Drawable backgroundDrawable = context.getDrawable(R.mipmap.ic_launcher_background);
Drawable vectorDrawable = context.getDrawable(R.drawable.ic_launcher_main_foreground);
AdaptiveIconDrawable adaptiveIconDrawable = new AdaptiveIconDrawable(backgroundDrawable, vectorDrawable);
Bitmap bitmap = drawableToBitmap(adaptiveIconDrawable);
return bitmap;
}
}
private static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
This here is my icon (ic_main_white.xml)
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="45dp"
android:height="45dp"
android:viewportHeight="1024"
android:viewportWidth="1024">
<path
android:fillColor="#FFFFFF"
android:pathData="M511.5 74C269.87847 74 74 269.87847 74 511.5 74 753.13368 269.87847 949 511.5 949 753.12153 949 949 753.13368 949 511.5 949 269.87847 753.12153 74 511.5 74l0 0 0 0 0 0zm30.10243 764.20312l0 -140.08506 -57.72569 0 0 140.27951C325.65972 825.12674 199.05208 699.1875 184.78472 541.25l142.21181 0 0 -57.72569 -142.34549 0C198.12847 324.77257 325.07639 197.95833 483.87674 184.63889l0 142.00521 57.72569 0 0 -141.81077c157.64583 14.40104 283.32986 140.76563 296.74653 298.69098l-139.87847 0 0 57.72569 139.74479 0C824.02083 698.34896 698.66493 823.85069 541.60243 838.20312l0 0z"/>
</vector>
Using the Android Asset Generator I created an Image Asset where I get all the needed files generated. This is the same process you would go through when creating an adaptive icon for your app's launcher icon.
But the result is only a part of the icon being shown, it looks like the generated icon is to big for what it's expected or I'm missing something somewhere.
Also there is this documentation where following is stated:
For dynamic shortcuts, call the createWithAdaptiveBitmap() method when
you create them.
The icons are generated by Android Studio itself and this also works with my launcher's icon, but why is it not working right using createWithAdaptiveBitmap? Am I missing some java code or do you know of an example using adaptive icons with shortcuts, I could not find anything that worked on GitHub or somewhere else.

Here's what I use:
fun convertAppIconDrawableToBitmap(context: Context, drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable)
return drawable.bitmap
val appIconSize = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && drawable is AdaptiveIconDrawable)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 108f, context.resources.displayMetrics).toInt()
else getAppIconSize(context)
return drawable.toBitmap(appIconSize, appIconSize, Bitmap.Config.ARGB_8888)
}
fun getAppIconSize(context: Context): Int {
val activityManager = ContextCompat.getSystemService(this, ActivityManager::class.java)!!
val appIconSize = try {
activityManager.launcherLargeIconSize
} catch (e: Exception) {
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48f, context.resources.displayMetrics).toInt()
}
return appIconSize
}

For the solution you need:
When you generate the icon with the asset manager in Android Studio make sure the icon resides inside the "secure area", it is really important the assets have the correct size (see https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive)
The convertion to bitmap is key:
private static Bitmap drawableToBitmap(final Drawable drawable, final Context context) {
final float screenDensity = context.getResources().getDisplayMetrics().density;
final int adaptiveIconSize = Math.round(ADAPTIVE_ICON_SIZE_DP * screenDensity);
final int adaptiveIconOuterSides = Math.round(ADAPTIVE_ICON_OUTER_SIDES_DP * screenDensity);
final Bitmap bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
drawable.setBounds(adaptiveIconOuterSides, adaptiveIconOuterSides, adaptiveIconSize - adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides);
drawable.draw(canvas);
return bitmap;
}

Related

How to convert SkiaSharp.SkBitmap to Android.Graphics.Bitmap?

I want to convert PinBitmap (SkiaSharp.SkBitmap) to Android.Graphics.Bitmap. I couldn't find online references, I only tried this in the Android project:
Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeByteArray(myView.PinBitmap.Bytes, 0, myView.PinBitmap.Bytes.Length);
but the bitmap is null.
I'm creating the PinBitmap from a SKCanvasView:
private void SKCanvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
var surface = e.Surface;
var canvas = surface.Canvas;
SKImageInfo info = e.Info;
canvas.DrawLine(10, 10, 10, 200, new SKPaint() { IsStroke = true, Color = SKColors.Green, StrokeWidth = 10 });
SKBitmap saveBitmap = new SKBitmap();
// Create bitmap the size of the display surface
if (saveBitmap == null)
{
saveBitmap = new SKBitmap(info.Width, info.Height);
}
// Or create new bitmap for a new size of display surface
else if (saveBitmap.Width < info.Width || saveBitmap.Height < info.Height)
{
SKBitmap newBitmap = new SKBitmap(Math.Max(saveBitmap.Width, info.Width),
Math.Max(saveBitmap.Height, info.Height));
using (SKCanvas newCanvas = new SKCanvas(newBitmap))
{
newCanvas.Clear();
newCanvas.DrawBitmap(saveBitmap, 0, 0);
}
saveBitmap = newBitmap;
}
// Render the bitmap
canvas.Clear();
canvas.DrawBitmap(saveBitmap, 0, 0);
var customPin = new CustomPin { PinBitmap = saveBitmap };
Content = customPin;
}
This is easy to do, you just need to have the SkiaSharp.Views NuGet
package installed. Then, there are extension methods:
skiaBitmap = androidBitmap.ToSKBitmap();
androidBitmap = skiaBitmap.ToBitmap();
There are also a few others, like: ToSKImage
and ToSKPixmap.
NOTE: these all make copies of the pixel data. To avoid memory issue,
you can dispose of the original as soon as the method returns.
Source: https://forums.xamarin.com/discussion/comment/294868/#Comment_294868
I want to convert PinBitmap (SkiaSharp.SkBitmap) to Android.Graphics.Bitmap
In Android MainActivity, you could use AndroidExtensions.ToBitmap Method to convert PinBitmap to Bitmap.
AndroidExtensions.ToBitmap Method: https://learn.microsoft.com/en-us/dotnet/api/skiasharp.views.android.androidextensions.tobitmap?view=skiasharp-views-1.68.1
Install SkiaSharp.Views.Forms from NuGet Package. https://www.nuget.org/packages/SkiaSharp.Views.Forms/
Use the reference.
using SkiaSharp.Views.Android;
Use the code below.
var bitmap = AndroidExtensions.ToBitmap(PinBitmap);

Can I create a GaussianBlur effect via an svg file? [duplicate]

I have an imageview and i set Image Resources programmatically like this:
int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);
Is there any easy way to show my ImageView with blurry image?
You can use glide transformations
https://github.com/wasabeef/glide-transformations
you can blur the image with one line of code
Glide.with(this).load(R.drawable.demo)
.bitmapTransform(new BlurTransformation(context))
.into((ImageView) findViewById(R.id.image));
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
Bitmap blurred = blurRenderScript(this,yourBitmap, 25);
//second parametre is radius
yourImageView.setImageBitmap(blurred);
#SuppressLint("NewApi")
public static Bitmap blurRenderScript(Context context,Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(context);
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private static Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
There are many libraries are available you can use any of these.
I prefer Blurry library for it.
it is very simple and optimized.
dependency:
dependencies {
compile 'jp.wasabeef:blurry:4.x.x'
}
Functions
Blurry.with(context).radius(25).sampling(2).onto(rootView)
// from View
Blurry.with(context).capture(view).into(imageView)
// from Bitmap
Blurry.with(context).from(bitmap).into(imageView)
Blur Options
Radius
Down Sampling
Color Filter
Asynchronous Support
Animation (Overlay Only)
Blurry.with(context)
.radius(10)
.sampling(8)
.color(Color.argb(66, 255, 255, 0))
.async()
.animate(500)
.onto(rootView);
Get a bitmap directly
// Sync
val bitmap = Blurry.with(this)
.radius(10)
.sampling(8)
.capture(findViewById(R.id.right_bottom)).get()
imageView.setImageDrawable(BitmapDrawable(resources, bitmap))
// Async
Blurry.with(this)
.radius(25)
.sampling(4)
.color(Color.argb(66, 255, 255, 0))
.capture(findViewById(R.id.left_bottom))
.getAsync {
imageView.setImageDrawable(BitmapDrawable(resources, it))
}
private Bitmap CreateBlurredImage (int radius)
{
// Load a clean bitmap and work from that
Bitmap originalBitmap=
BitmapFactory.DecodeResource(Resources,Resource.Drawable.dog_and_monkeys);
// Create another bitmap that will hold the results of the filter.
Bitmap blurredBitmap;
blurredBitmap = Bitmap.CreateBitmap (originalBitmap);
// Create the Renderscript instance that will do the work.
RenderScript rs = RenderScript.Create (this);
// Allocate memory for Renderscript to work with
Allocation input = Allocation.CreateFromBitmap (rs, originalBitmap, Allocation.MipmapControl.MipmapFull, AllocationUsage.Script);
Allocation output = Allocation.CreateTyped (rs, input.Type);
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.Create (rs, Element.U8_4 (rs));
script.SetInput (input);
// Set the blur radius
script.SetRadius (radius);
// Start the ScriptIntrinisicBlur
script.ForEach (output);
// Copy the output to the blurred bitmap
output.CopyTo (blurredBitmap);
return blurredBitmap;
}
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
_imageView = FindViewById<ImageView> (Resource.Id.originalImageView);
_seekbar = FindViewById<SeekBar> (Resource.Id.seekBar1);
_seekbar.StopTrackingTouch += BlurImageHandler;
}
private void BlurImageHandler (object sender, SeekBar.StopTrackingTouchEventArgs e)
{
int radius = e.SeekBar.Progress;
if (radius == 0) {
// We don't want to blur, so just load the un-altered image.
_imageView.SetImageResource (Resource.Drawable.dog_and_monkeys);
} else {
DisplayBlurredImage (radius);
}
}
private void DisplayBlurredImage (int radius)
{
_seekbar.StopTrackingTouch -= BlurImageHandler;
_seekbar.Enabled = false;
ShowIndeterminateProgressDialog ();
Task.Factory.StartNew (() => {
Bitmap bmp = CreateBlurredImage (radius);
return bmp;
})
.ContinueWith (task => {
Bitmap bmp = task.Result;
_imageView.SetImageBitmap (bmp);
_seekbar.StopTrackingTouch += BlurImageHandler;
_seekbar.Enabled = true;
DismissIndeterminateProgressDialog ();
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar1"
android:max="25" />
<ImageView
android:src="#drawable/dog_and_monkeys"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/originalImageView" />
</LinearLayout>
click here deatiled code example
Just simply use this library https://github.com/ChathuraHettiarachchi/BlurIM
, I was having problem with BlurTransformation class had errors thats why couldn't use Glide transformation but this works fine.
BlurImage.withContext(this)
.blurFromResource(R.drawable.YOUR_RESOURCE)
.into(imageView);
Originally answered here
Android 12 Preview 1 comes with built-in blur feature. We need not depend on external library now. Here is the code
imageView.setRenderEffect(
RenderEffect.createBlurEffect(
20.0f, 20.0f, SHADER_TITLE_MODE
)
)
You can use RenderScript to accomblish that as explained here or you can use the stackblur library to make a blurring effect in your image.
Usage of the stackblur library:
int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
// get bitmap from resource id
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
StackBlurManager stackBlurManager = new StackBlurManager(bitmap);
// process the image using a certain radius
stackBlurManager.process(progress*4);
// obtain the image and load it into an ImageView or any other component
imgLock.setImageBitmap(stackBlurManager.returnBlurredImage());
There's the library that can use RenderScript so a blurring is blazingly fast and super easy to use:
<ru.egslava.blurredview.BlurredImageView
...
android:src="#drawable/..."
app:radius="0.3"
app:keepOriginal="true"
app:downSampling="2" />
Add dependencies
compile 'jp.wasabeef:fresco-processors:2.1.0'
Use following code in layout file:
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use following code in your java file:
SimpleDraweeView imgView = (SimpleDraweeView) findViewById(R.id.imageView);
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setPostprocessor(new IterativeBoxBlurPostProcessor(20))
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(imgView.getController())
.build();
imgView.setController(controller);
You can also blur an ImageView by using Coil library.
image.load("http://xxx.jpg") {
transformations(BlurTransformation(applicationContext,20f))
}
Late here but I got an error trying to use bitmaptransfrom directly after load. If you are facing the same, use:
Glide.with(mContext).load(drawable).apply(RequestOptions.bitmapTransform(new BlurTransformation())).into(imageView);
There are different ways to make view blur in android, But i found the easiest and fastest way to make views blur using Fresco library.
Add following dependency inside your build.gradle of your module.
compile 'jp.wasabeef:fresco-processors:2.1.0'
And inside onCreate() of Activity.
Fresco.initialize(this);
setContentView(R.layout.activity_main);
SimpleDraweeView simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);
//INSTANTIATE BLUR POST PROCESSOR
Postprocessor postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);
//INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
.setPostprocessor(postprocessor)
.build();
//INSTANTATE CONTROLLOR()
PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
.setImageRequest(imageRequest)
.setOldController(simpleDraweeView.getController())
.build();
//LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
simpleDraweeView.setController(controller);
If you need complete implementation please visit this blog
Fastest Image Blur in Android Using Fresco.
This is simple method
set blur color with alpha
public class BlurImageView extends ImageView {
Paint rectPaint;
private int blurcolor=Color.parseColor("#aeffffff");
public BlurImageView(Context context) {
this(context, null);
}
public BlurImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BlurImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
rectPaint=new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Paint.Style.FILL);
rectPaint.setColor(blurcolor);
invalidate();
}
public void setBlurcolor(int blurcolor) {
this.blurcolor = blurcolor;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("BlurImageView","canvas");
canvas.drawRect(getLeft(),0,getRight(),getHeight(),rectPaint);
}
}

manipulate the colours in a Bitmap android

I have a QrCode which i want to change its colours to white and blue...
I can do it using the following code:
val bitmap = qrgEncoder.encodeAsBitmap()
val width = bitmap.width
val height = bitmap.height
// All are 0, or black, by default
for (y in 0 until height) {
for (x in 0 until width) {
bitmap.getPixel(x, y).also {
if(it != -1)
bitmap.setPixel(x, y, ResourcesCompat.getColor(resources, R.color.defaultTextColor, null))
else
bitmap.setPixel(x, y, ResourcesCompat.getColor(resources, R.color.toolbarColor, null))
}
}
}
// Setting Bitmap to ImageView
qrImage.setImageBitmap(bitmap)
but this is too slow... so I am wondering what is the best approach to do the same thing and faster.
After trying different solutions, I realised the only way is to manipulate the pixels.
The following code is the optimum solution for now:
val pixelsArray = IntArray(mWidth * mHeight)
val newColor1 = getColor(context!!, R.color.color1)
val newColor2 = getColor(context!!, R.color.color2)
bitmap.getPixels(pixelsArray, 0, mWidth, 0, 0, mWidth, mHeight)
for (y in 0 until pixelsArray.size) {
if (pixelsArray[y] != -1)
pixelsArray[y] = newColor1
else
pixelsArray[y] = newColor2
}
note for accepted answer by msc87,
to save pixelsArray back to bitmap use:
bitmap.setPixels(pixelsArray,0,mWidth,0,0,mWidth,maskHeight)
you can also replace getColour to: (if needed)
Color.argb(255,0,177,64)
ect..
You can set a Drawable tint:
https://developer.android.com/reference/android/support/v4/graphics/drawable/DrawableCompat.html#setTint(android.graphics.drawable.Drawable,%20int)
val bitmap: Bitmap = ...
val bitmapDrawable = BitmapDrawable(resources, bitmap)
DrawableCompat.setTint(bitmapDrawable, Color.BLUE)

How to blur imageview in android

I have an imageview and i set Image Resources programmatically like this:
int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);
Is there any easy way to show my ImageView with blurry image?
You can use glide transformations
https://github.com/wasabeef/glide-transformations
you can blur the image with one line of code
Glide.with(this).load(R.drawable.demo)
.bitmapTransform(new BlurTransformation(context))
.into((ImageView) findViewById(R.id.image));
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
Bitmap blurred = blurRenderScript(this,yourBitmap, 25);
//second parametre is radius
yourImageView.setImageBitmap(blurred);
#SuppressLint("NewApi")
public static Bitmap blurRenderScript(Context context,Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(context);
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private static Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
There are many libraries are available you can use any of these.
I prefer Blurry library for it.
it is very simple and optimized.
dependency:
dependencies {
compile 'jp.wasabeef:blurry:4.x.x'
}
Functions
Blurry.with(context).radius(25).sampling(2).onto(rootView)
// from View
Blurry.with(context).capture(view).into(imageView)
// from Bitmap
Blurry.with(context).from(bitmap).into(imageView)
Blur Options
Radius
Down Sampling
Color Filter
Asynchronous Support
Animation (Overlay Only)
Blurry.with(context)
.radius(10)
.sampling(8)
.color(Color.argb(66, 255, 255, 0))
.async()
.animate(500)
.onto(rootView);
Get a bitmap directly
// Sync
val bitmap = Blurry.with(this)
.radius(10)
.sampling(8)
.capture(findViewById(R.id.right_bottom)).get()
imageView.setImageDrawable(BitmapDrawable(resources, bitmap))
// Async
Blurry.with(this)
.radius(25)
.sampling(4)
.color(Color.argb(66, 255, 255, 0))
.capture(findViewById(R.id.left_bottom))
.getAsync {
imageView.setImageDrawable(BitmapDrawable(resources, it))
}
private Bitmap CreateBlurredImage (int radius)
{
// Load a clean bitmap and work from that
Bitmap originalBitmap=
BitmapFactory.DecodeResource(Resources,Resource.Drawable.dog_and_monkeys);
// Create another bitmap that will hold the results of the filter.
Bitmap blurredBitmap;
blurredBitmap = Bitmap.CreateBitmap (originalBitmap);
// Create the Renderscript instance that will do the work.
RenderScript rs = RenderScript.Create (this);
// Allocate memory for Renderscript to work with
Allocation input = Allocation.CreateFromBitmap (rs, originalBitmap, Allocation.MipmapControl.MipmapFull, AllocationUsage.Script);
Allocation output = Allocation.CreateTyped (rs, input.Type);
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.Create (rs, Element.U8_4 (rs));
script.SetInput (input);
// Set the blur radius
script.SetRadius (radius);
// Start the ScriptIntrinisicBlur
script.ForEach (output);
// Copy the output to the blurred bitmap
output.CopyTo (blurredBitmap);
return blurredBitmap;
}
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
_imageView = FindViewById<ImageView> (Resource.Id.originalImageView);
_seekbar = FindViewById<SeekBar> (Resource.Id.seekBar1);
_seekbar.StopTrackingTouch += BlurImageHandler;
}
private void BlurImageHandler (object sender, SeekBar.StopTrackingTouchEventArgs e)
{
int radius = e.SeekBar.Progress;
if (radius == 0) {
// We don't want to blur, so just load the un-altered image.
_imageView.SetImageResource (Resource.Drawable.dog_and_monkeys);
} else {
DisplayBlurredImage (radius);
}
}
private void DisplayBlurredImage (int radius)
{
_seekbar.StopTrackingTouch -= BlurImageHandler;
_seekbar.Enabled = false;
ShowIndeterminateProgressDialog ();
Task.Factory.StartNew (() => {
Bitmap bmp = CreateBlurredImage (radius);
return bmp;
})
.ContinueWith (task => {
Bitmap bmp = task.Result;
_imageView.SetImageBitmap (bmp);
_seekbar.StopTrackingTouch += BlurImageHandler;
_seekbar.Enabled = true;
DismissIndeterminateProgressDialog ();
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar1"
android:max="25" />
<ImageView
android:src="#drawable/dog_and_monkeys"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/originalImageView" />
</LinearLayout>
click here deatiled code example
Just simply use this library https://github.com/ChathuraHettiarachchi/BlurIM
, I was having problem with BlurTransformation class had errors thats why couldn't use Glide transformation but this works fine.
BlurImage.withContext(this)
.blurFromResource(R.drawable.YOUR_RESOURCE)
.into(imageView);
Originally answered here
Android 12 Preview 1 comes with built-in blur feature. We need not depend on external library now. Here is the code
imageView.setRenderEffect(
RenderEffect.createBlurEffect(
20.0f, 20.0f, SHADER_TITLE_MODE
)
)
You can use RenderScript to accomblish that as explained here or you can use the stackblur library to make a blurring effect in your image.
Usage of the stackblur library:
int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
// get bitmap from resource id
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
StackBlurManager stackBlurManager = new StackBlurManager(bitmap);
// process the image using a certain radius
stackBlurManager.process(progress*4);
// obtain the image and load it into an ImageView or any other component
imgLock.setImageBitmap(stackBlurManager.returnBlurredImage());
There's the library that can use RenderScript so a blurring is blazingly fast and super easy to use:
<ru.egslava.blurredview.BlurredImageView
...
android:src="#drawable/..."
app:radius="0.3"
app:keepOriginal="true"
app:downSampling="2" />
Add dependencies
compile 'jp.wasabeef:fresco-processors:2.1.0'
Use following code in layout file:
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use following code in your java file:
SimpleDraweeView imgView = (SimpleDraweeView) findViewById(R.id.imageView);
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setPostprocessor(new IterativeBoxBlurPostProcessor(20))
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(imgView.getController())
.build();
imgView.setController(controller);
You can also blur an ImageView by using Coil library.
image.load("http://xxx.jpg") {
transformations(BlurTransformation(applicationContext,20f))
}
Late here but I got an error trying to use bitmaptransfrom directly after load. If you are facing the same, use:
Glide.with(mContext).load(drawable).apply(RequestOptions.bitmapTransform(new BlurTransformation())).into(imageView);
There are different ways to make view blur in android, But i found the easiest and fastest way to make views blur using Fresco library.
Add following dependency inside your build.gradle of your module.
compile 'jp.wasabeef:fresco-processors:2.1.0'
And inside onCreate() of Activity.
Fresco.initialize(this);
setContentView(R.layout.activity_main);
SimpleDraweeView simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);
//INSTANTIATE BLUR POST PROCESSOR
Postprocessor postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);
//INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
.setPostprocessor(postprocessor)
.build();
//INSTANTATE CONTROLLOR()
PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
.setImageRequest(imageRequest)
.setOldController(simpleDraweeView.getController())
.build();
//LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
simpleDraweeView.setController(controller);
If you need complete implementation please visit this blog
Fastest Image Blur in Android Using Fresco.
This is simple method
set blur color with alpha
public class BlurImageView extends ImageView {
Paint rectPaint;
private int blurcolor=Color.parseColor("#aeffffff");
public BlurImageView(Context context) {
this(context, null);
}
public BlurImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BlurImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
rectPaint=new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Paint.Style.FILL);
rectPaint.setColor(blurcolor);
invalidate();
}
public void setBlurcolor(int blurcolor) {
this.blurcolor = blurcolor;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("BlurImageView","canvas");
canvas.drawRect(getLeft(),0,getRight(),getHeight(),rectPaint);
}
}

Convert String to Drawable

I want to raise a notification showing an icon in the status bar - so far so good, but actually I would like this icon to be a 3 character String.
So my question is: Is there a way to convert my String into a Drawable to display it as Icon in the status bar?
EDIT: I recently found an app which does something similar - Battery Indicator
It shows the current battery level as notification icon in the status bar - I wonder if it really uses different 100 images
Short: No, you can't.
Long: The notification needs a R.drawable.something for the icon and you can't create it on runtime.
public Drawable getDrawable(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
Drawable d =new BitmapDrawable(BitmapFactory.decodeStream(url.openConnection().getInputStream()));
return d;
}
catch(Exception ex) {return null;}
}
you can make your own custom drawable that would work just like the textview widget except it is a drawable instead of a view. The textview class is just a container for the drawable that contains the text.
I have used a workaround and it worked properly for me.
First i convert the string to bitmap and then convert it to a drawable, here is the code:
byte [] encodeByte=Base64.decode(":",Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
Drawable d = new BitmapDrawable(bitmap);
Hope it helps!
Have you looked at the API Demos > App > Notifications > Status Bar?
If you have limited number of String options (like Smileys) you can create drawables for each of those Strings.
No you can not, I thought you could use the same method as here: Combine image and text to drawable, but you can't, as the notification takes a drawable id, not a drawable object.
(I know this doesn't answer the OP's question fully, but the title got me here since it's pretty general.)
After fiddling around a bit, I've come up with this solution. It's pretty messy and could probably be improved, but it works.
In its current form, the function takes the first letter of the String it's passed and a unique ID for that String. The ID is only used for background color generation and remembering it, so it can be removed if you're going to use a steady color.
I made this to generate default images for contacts that don't have images saved, but it should be easy to adapt. It also happens to return an InputStream instead of a Drawable, but you can either just return bitmap after drawing to it, or use Drawable.createFromStream().
private static InputStream returnDefaultContact(Context context, String name, long id) {
Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(110);
int color = PreferenceManager.getDefaultSharedPreferences(context).getInt("contact_by_id_" + id, 0);
if (color == 0) {
int colorValue1 = (int)((56 + Math.random() * 200));
int colorValue2 = (int)((56 + Math.random() * 200));
int colorValue3 = (int)((56 + Math.random() * 200));
color = Color.rgb(colorValue1, colorValue2, colorValue3);
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt("contact_by_id_" + id, color).apply();
}
Paint backgroundPaint = new Paint();
backgroundPaint.setColor(color);
Bitmap bitmap = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, backgroundPaint);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.drawText(name.substring(0, 1), xPos, yPos, textPaint);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
return new ByteArrayInputStream(imageInByte);
}
try {
InputStream inputStream = new URL(Your imageWebAddress).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
}
catch (MalformedURLException ex) { }
catch (IOException ex) { }
layout.setBackground(drawable);

Categories

Resources