Drawable to bitmap kotlin

Android KTX

Kotlin упростил написание кода по сравнению с Java, но нет предела совершенству. Благодаря гибкости Kotlin можно создавать расширения к существующим классам и сделать код ещё проще. Чтобы не изобретать велосипед каждый раз, наиболее удачные примеры решили выделить в отдельную группу, которая получила название Android KTX.

Подключаем библиотеку (один из вариантов).

 // добавьте в секцию android kotlinOptions < jvmTarget = JavaVersion.VERSION_1_8.toString() >// для секции dependencies implementation 'androidx.core:core-ktx:1.2.0' //fragment implementation 'androidx.fragment:fragment-ktx:' // pallete implementation 'androidx.pallete:palette-ktx:' //SQLite implementation 'androidx.sqlite:sqlite-ktx:' // collections implementation 'androidx.collection:collection-ktx:' 

Примеры

Несколько примеров для знакомства.

Uri

Если у вас есть строка, которую нужно перевести в Uri, то писали следующую конструкцию.

 val uriString = "http://developer.alexanderklimov.ru/android" val uriOld = Uri.parse(uriString) Log.d("KTX", uri.host) 

Теперь можно писать проще. Код стал читаемым.

 val uriString = "http://developer.alexanderklimov.ru/android" val uri = uriString.toUri() Log.d("KTX", uri.host) 

SharedPreferences

При работе с файлами настройки приходится писать однотипный код.

 sharedPreferences.edit() .putBoolean(key, value) .apply() 

Сокращаем код. Разница не слишком большая, но выглядит опрятнее.

Bitmap/Drawable

 // get a drawable from resources va myDrawable = ContextCompat.getDrawable(context, R.drawable.cat) // convert the drawable to a bitmap val bitmap = myDrawable.toBitmap() 

Масштабируем Bitmap с помощью scale()

Удобная функция scale() поможет изменить размеры картинки.

 // get bitmap from drawable resource val bitmap = BitmapFactory.decodeResource(resources,R.drawable.table_cat) // scale bitmap using android ktx val scaledBitmap = bitmap.scale( 300, // width 300, // height false // filter ) button.setOnClickListener

View.drawToBitmap

Конвертирует компонент в изображение. Создадим карточку CardView и созданное изображение карточки поместим в ImageView.

 package ru.alexanderklimov.ktx import android.graphics.Bitmap import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.drawToBitmap import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener < // draw a bitmap from cardView val bitmap: Bitmap = cardView.drawToBitmap(Bitmap.Config.ARGB_8888) // show to generated bitmap to imageView imageView.setImageBitmap(bitmap) >> > 

Span

 val string = buildSpannedString < append("no styling text") bold < append("bold") italic < append("bold and italic) >> inSpans(RelativeSizeSpan(2f), QuoteSpan()) < append("double sized quote text") >> 

Bundle

 val bundle = bundleOf( "KEY_INT" to 1, "KEY_LONG" to 2L, "KEY_BOOLEAN" to true, "KEY_NULL" to null, "KEY_ARRAY" to arrayOf(1, 2, 3) ) 

Обратите внимание, что в примерах используется пакет androidx, это позволит не путать их с стандартными пакетами android.

Другие примеры из разных источников.

 //default usage supportFragmentManager .beginTransaction() .replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG ) .commitAllowingStateLoss() // using androidx.fragment:fragment-ktx supportFragmentManager.transaction( allowStateLosss = true ) < replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG) >// using androidx.core:core-ktx val s = "Hello, Spans!".toSpannable() val bold = StyleSpan(BOLD) s += bolds[7..12] = ForegroundColorSpan(Color.RED) // using androidx.core:core-ktx menu.forEach < // do action >// check if an itme is in the menu and remove it if(menuItem in menu) menu -= menuItem // default usage db.beginTransaction() try < // insert data db.setTransactionSuccessful() >finally < db.endTransaction() >// using androidx.sqlite:sqlite-ktx db.transaction < // insert data >

Источник

How to convert a Drawable to a Bitmap in Android using Kotlin?

This example demonstrates how to convert a Drawable to a Bitmap in Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

Step 3 − Add the following code to src/MainActivity.kt

import android.graphics.BitmapFactory import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val imageView: ImageView = findViewById(R.id.imageView) val btnConvert: Button = findViewById(R.id.btnConvert) btnConvert.setOnClickListener < val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image) imageView.setImageBitmap(bitmap) Toast.makeText(applicationContext, "Image converted to Bitmap", Toast.LENGTH_SHORT).show() >> >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

Convert drawable to Bitmap in Android compose example

In this compose example we are creating image by convert Drawable to Bitmap and adding this bitmap to Image compose widget. Generally we will add images inside drawable resource folder. From there we can add them to image.

In Compose we have different way to apply drawable to image

Read drawable from Resource :

Image Constructor with Painter we can directly read drawable resource and apply to image.

@Composable fun Image( painter: Painter, contentDescription: String?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null )
Image( // in this image we are specifying our drawable file // which we have to display on below line. painter = painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = "Android", alignment = Alignment.Center )

Convert Drawable to Bitmap

In the second way frist we are reading the Drawable from resource folder and then converting this drawable to bitmap and applying to Image

Constructor for Image with Bitmap parameter

@Composable fun Image( bitmap: ImageBitmap, contentDescription: String?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality )
val bitmap = getBitmapFromImage(ctx, R.drawable.download) Image( modifier = Modifier .height(200.dp) .width(200.dp), bitmap = bitmap, contentDescription = "Android Compose", alignment = Alignment.Center )

// This function creating the Bitmap by converting drawable resource @Composable private fun getBitmapFromImage(context: Context, drawable: Int): ImageBitmap

Now let run the application on your emulator/device you will see below output

Convert Drawable to Bitmap in Android compose example

Complete example code to convert Drawable to Bitmap in Android Compose

package rrtutors.com.composetextexample import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.DrawableContainer import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.Role.Companion.Image import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import rrtutors.com.composetextexample.ui.theme.greenColor @Composable fun drawbleToBitmap() < Scaffold( // in scaffold we are specifying top bar. topBar = < // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // Apply Title for the Topbar title = < Text( text = "Image to Bitmap", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = Color.White ) >) >) < //Here we are calling our actual functionality to show images drawableToBitmap() >> // Here we are created a simple compose function which will have the ui functionality @Composable fun drawableToBitmap() < val ctx = LocalContext.current // on below line we are creating a column for our ui. Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .fillMaxSize() .padding(6.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) < Text( modifier = Modifier.padding(6.dp), text = "Normal Image", fontWeight = FontWeight.Bold, color = greenColor, fontSize = 20.sp ) // Adding the Space between compose widgets by using Spacer Spacer(modifier = Modifier.height(20.dp)) // Create image from Resource drawable by Painter property Image( // in this image we are specifying our drawable file // which we have to display on below line. painter = painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = "Android", alignment = Alignment.Center ) // on below line we are specifying spacer of height 20 Spacer(modifier = Modifier.height(20.dp)) Text( modifier = Modifier.padding(6.dp), text = "Bitmap Image", fontWeight = FontWeight.Bold, color = greenColor, fontSize = 20.sp ) // on below line we are specifying spacer of height 20 Spacer(modifier = Modifier.height(20.dp)) val bitmap = getBitmapFromImage(ctx, R.drawable.download) Image( modifier = Modifier .height(200.dp) .width(200.dp), bitmap = bitmap, contentDescription = "Android Compose", alignment = Alignment.Center ) >> // This function creating the Bitmap by converting drawable resource @Composable private fun getBitmapFromImage(context: Context, drawable: Int): ImageBitmap

Источник

How to Convert a Drawable to a Bitmap

How to load an image from drawable and convert to a bitmap

The following method should work fine:

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) Drawable drawable = ContextCompat.getDrawable(context, drawableId); 
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) drawable = (DrawableCompat.wrap(drawable)).mutate();
>
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;
>
dependencies classpath 'com.android.tools.build:gradle:2.2.0-alpha5' 
>
android compileSdkVersion 23 
buildToolsVersion '23.0.3'
defaultConfig minSdkVersion 16
targetSdkVersion 23
vectorDrawables.useSupportLibrary = true
>
.
>
.

Or, you can use android-ktx in Kotlin too like this which works for any subclass of Drawable :

dependencies implementation 'androidx.core:core-ktx:1.0.0-alpha1'
>

Then use Drawable#toBitmap() like this:

val bitmap = AppCompatResources.getDrawable(requireContext(), drawableId).toBitmap()

How to create Bitmap form Drawable object

You can convert your Drawable to Bitmap like this (for resource):

Bitmap icon = BitmapFactory.decodeResource(context.getResources(), 
R.drawable.drawable_source);

If you’ve it stored in a variable, you can use this :

public static Bitmap drawableToBitmap (Drawable drawable) Bitmap bitmap = null;

if (drawable instanceof BitmapDrawable) BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) return bitmapDrawable.getBitmap();
>
>

if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
> else 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;
>

Getting Bitmap from vector drawable

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) Drawable drawable = ContextCompat.getDrawable(context, drawableId); 
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) drawable = (DrawableCompat.wrap(drawable)).mutate();
>

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;
>
dependencies classpath 'com.android.tools.build:gradle:2.2.0-alpha5' 
>
android compileSdkVersion 23 
buildToolsVersion '23.0.3'
defaultConfig minSdkVersion 16
targetSdkVersion 23
vectorDrawables.useSupportLibrary = true
>
.
>
.

converting drawable resource image into bitmap

You probably mean Notification.Builder.setLargeIcon(Bitmap) , right? 🙂

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);

This is a great method of converting resource images into Android Bitmap s.

How to convert a Drawable to a scaled Bitmap

With pskink’s answer (Make Image view rounded (not the image)) to a similar question I came to the following solution, based on the saveLayer approach (with some minor modifications).

@Override
public void onDraw( Canvas canvas )
Paint paint1 = new Paint( Paint.ANTI_ALIAS_FLAG )
Paint paint2 = new Paint()
paint2.setXfermode( new PorterDuffXfermode( Mode.SRC_IN ) )

Drawable drawable = getDrawable()
RectF rectangle = new RectF()
rectangle.set( drawable.getBounds() )

getImageMatrix.mapRect( rectangle )
rectangle.offset( getPaddingLeft(), getPaddingTop() )

// Prevent radius being drawn out of canvas bounds
rectangle.intersect( new RectF( 0, 0, canvas.getWidth(), canvas.getHeight() ) )

int restore = canvas.saveLayer( rectangle, null, Canvas.ALL_SAVE_FLAG )
canvas.drawRoundRect( rectangle, radius.getValue(), radius.getValue(), paint1 )
canvas.saveLayer( rectangle, paint2, Canvas.ALL_SAVE_FLAG )
super.onDraw( canvas )
canvas.restoreToCount( restore )
>

The above code ignores object caching in class level and ignores NPE from getDrawable().

How to convert a Bitmap to Drawable in android?

Sounds like you want to use BitmapDrawable

A Drawable that wraps a bitmap and can
be tiled, stretched, or aligned. You
can create a BitmapDrawable from a
file path, an input stream, through
XML inflation, or from a Bitmap
object.

Источник

Читайте также:  Cfg hacked css v34
Оцените статью