如何创建位图表单Drawable对象 [英] How to create Bitmap form Drawable object

查看:95
本文介绍了如何创建位图表单Drawable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Android开发自定义视图.为此,我想赋予用户选择和成像的能力,就像使用ImageView

I am developing custom view for android. For that I want give a user ability to select and image using just like when using ImageView

attr.xml 中,我添加了以下代码.

In attr.xml I added bellow code.

<declare-styleable name="DiagonalCut">
    <attr name="altitude" format="dimension"/>
    <attr name="background_image" format="reference"/>
</declare-styleable>

在自定义视图中,我将此值作为Drawable来获取,该值在xml中以app:background_image="@drawable/image"

In custom view I get this value as a Drawable which was provided in xml as app:background_image="@drawable/image"

TypedArray typedArray = getContext().obtainStyledAttributes(arr, R.styleable.DiagonalCut);
altitude = typedArray.getDimensionPixelSize(R.styleable.DiagonalCut_altitude,10);
sourceImage = typedArray.getDrawable(R.styleable.DiagonalCut_background_image);

我想使用此sourceImage(可绘制对象)创建位图.

I want to create a Bitmap using this sourceImage which is a Drawable object.

如果我要走错路,请提供替代方法.

If the way I'm going wrong please provide an alternative.

推荐答案

您可以像这样(用于资源)将Drawable转换为Bitmap:

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

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

OR

如果您将其存储在变量中,则可以使用以下方法:

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;
}

更多详细信息

这篇关于如何创建位图表单Drawable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆