热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何创建可绘制对象的位图

如何解决《如何创建可绘制对象的位图》经验,为你挑选了1个好方法。

我正在为android开发自定义视图.为此我想让用户能够选择和使用图像,就像使用时一样ImageView

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


    
    

在自定义视图中,我得到的值Drawable是xml中提供的值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它创建一个Bitmap ,这是一个Drawable对象.

如果我出错的方式请提供替代方案.



1> Ashish Ranja..:

您可以将您转换DrawableBitmap这样(对于资源):

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

要么

如果它存储在变量中,您可以使用:

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

更多细节


推荐阅读
author-avatar
明恋夏日2
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有