Android:每次调用函数时,结果drawable中的图层顺序都不同

时间:2013-08-24 13:21:06

标签: android canvas bitmap drawable

我有以下代码:

public Drawable getMergedIcon(Drawable origIcon) {  
    Bitmap underlayBitmap = null, overlayBitmap = null;
    if (isSupportUnderlays()) {
        int overlayId = r.nextInt(Underlays.size());
        underlayBitmap = Underlays.get(overlayId);
        if(Overlays.size() == Underlays.size()) {
            overlayBitmap = Overlays.get(overlayId);
        }
        if(underlayBitmap == null) {
            return origIcon;
        }

        boolean needResize = false;
        int targetWidth, targetHeight;
        Bitmap iconBitmap = ((BitmapDrawable) origIcon).getBitmap();

        if(iconBitmap.getHeight() > underlayBitmap.getHeight()) {
            targetWidth = iconBitmap.getWidth();
            targetHeight = iconBitmap.getHeight();
            needResize = true;
        } else {
            targetWidth = underlayBitmap.getWidth();
            targetHeight = underlayBitmap.getHeight();
        }


        Paint paint = new Paint();

        Bitmap result = Bitmap.createBitmap(targetWidth, targetHeight, iconBitmap.getConfig());
        Canvas canvas = new Canvas(result);

        if(!needResize) {
            canvas.drawBitmap(underlayBitmap, 0, 0, paint);
        } else {
            canvas.drawBitmap(Bitmap.createScaledBitmap(underlayBitmap, targetWidth,targetHeight, false), 0, 0, paint);
        }
        int left = (targetHeight - (int) (targetHeight * iconScale)) / 2;
        int top = (targetWidth - (int) (targetWidth * iconScale)) / 2;
        iconBitmap = Bitmap.createScaledBitmap(iconBitmap, (int) (targetWidth * iconScale),(int) (targetHeight * iconScale), false);
        canvas.drawBitmap(iconBitmap, left, top, paint);

        if(overlayBitmap != null) {
            if(!needResize) {
                canvas.drawBitmap(overlayBitmap, 0, 0, paint);
            } else {
                canvas.drawBitmap(Bitmap.createScaledBitmap(overlayBitmap, targetWidth,targetHeight, false), 0, 0, paint);
            }
        }
        canvas.save();

        BitmapDrawable icon = new BitmapDrawable(mContext.getResources(), result);
        return icon; 
    }
    return origIcon;
} 

它需要覆盖和底层的随机位图,并在它之间放置图标 但当我调用此功能时,图层会随机丢失。 F.E.在第一次通话时我有底层和图标,在第二个叠加和图标等 我总是有图标,但只有一层(底层或叠加层),而且从不使用它们的机器人。

1 个答案:

答案 0 :(得分:0)

代码可行,是我的愚蠢错误...... 我只是把错误的drawable放在数组中。