1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.gallery3d.gadget;
18
19import android.content.Context;
20import android.content.res.Resources;
21import android.graphics.Bitmap;
22import android.graphics.Bitmap.Config;
23import android.graphics.Canvas;
24import android.graphics.Paint;
25import android.util.Log;
26
27import com.android.gallery3d.R;
28import com.android.gallery3d.data.MediaItem;
29import com.android.gallery3d.util.ThreadPool;
30
31public class WidgetUtils {
32
33    private static final String TAG = "WidgetUtils";
34
35    private static int sStackPhotoWidth = 220;
36    private static int sStackPhotoHeight = 170;
37
38    private WidgetUtils() {
39    }
40
41    public static void initialize(Context context) {
42        Resources r = context.getResources();
43        sStackPhotoWidth = r.getDimensionPixelSize(R.dimen.stack_photo_width);
44        sStackPhotoHeight = r.getDimensionPixelSize(R.dimen.stack_photo_height);
45    }
46
47    public static Bitmap createWidgetBitmap(MediaItem image) {
48        Bitmap bitmap = image.requestImage(MediaItem.TYPE_THUMBNAIL)
49               .run(ThreadPool.JOB_CONTEXT_STUB);
50        if (bitmap == null) {
51            Log.w(TAG, "fail to get image of " + image.toString());
52            return null;
53        }
54        return createWidgetBitmap(bitmap, image.getRotation());
55    }
56
57    public static Bitmap createWidgetBitmap(Bitmap bitmap, int rotation) {
58        int w = bitmap.getWidth();
59        int h = bitmap.getHeight();
60
61        float scale;
62        if (((rotation / 90) & 1) == 0) {
63            scale = Math.max((float) sStackPhotoWidth / w,
64                    (float) sStackPhotoHeight / h);
65        } else {
66            scale = Math.max((float) sStackPhotoWidth / h,
67                    (float) sStackPhotoHeight / w);
68        }
69
70        Bitmap target = Bitmap.createBitmap(
71                sStackPhotoWidth, sStackPhotoHeight, Config.ARGB_8888);
72        Canvas canvas = new Canvas(target);
73        canvas.translate(sStackPhotoWidth / 2, sStackPhotoHeight / 2);
74        canvas.rotate(rotation);
75        canvas.scale(scale, scale);
76        Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
77        canvas.drawBitmap(bitmap, -w / 2, -h / 2, paint);
78        return target;
79    }
80}
81