Example usage for android.graphics Canvas drawBitmap

List of usage examples for android.graphics Canvas drawBitmap

Introduction

In this page you can find the example usage for android.graphics Canvas drawBitmap.

Prototype

public void drawBitmap(@NonNull Bitmap bitmap, @NonNull Matrix matrix, @Nullable Paint paint) 

Source Link

Document

Draw the bitmap using the specified matrix.

Usage

From source file:Main.java

/**
 * A potentially expensive operation to crop the given Bitmap so that it fills the given dimensions. This operation
 * is significantly less expensive in terms of memory if a mutable Bitmap with the given dimensions is passed in
 * as well./*from   w w w  . j a  va2  s  . c om*/
 *
 * @param recycled A mutable Bitmap with dimensions width and height that we can load the cropped portion of toCrop
 *                 into
 * @param toCrop The Bitmap to resize
 * @param width The width of the final Bitmap
 * @param height The height of the final Bitmap
 * @return The resized Bitmap (will be recycled if recycled is not null)
 */
public static Bitmap centerCrop(Bitmap recycled, Bitmap toCrop, int width, int height) {
    if (toCrop == null) {
        return null;
    } else if (toCrop.getWidth() == width && toCrop.getHeight() == height) {
        return toCrop;
    }
    //from ImageView/Bitmap.createScaledBitmap
    //https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/ImageView.java
    //https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/graphics/java/android/graphics/Bitmap.java
    final float scale;
    float dx = 0, dy = 0;
    Matrix m = new Matrix();
    if (toCrop.getWidth() * height > width * toCrop.getHeight()) {
        scale = (float) height / (float) toCrop.getHeight();
        dx = (width - toCrop.getWidth() * scale) * 0.5f;
    } else {
        scale = (float) width / (float) toCrop.getWidth();
        dy = (height - toCrop.getHeight() * scale) * 0.5f;
    }

    m.setScale(scale, scale);
    m.postTranslate((int) dx + 0.5f, (int) dy + 0.5f);
    final Bitmap result;
    if (recycled != null) {
        result = recycled;
    } else {
        result = Bitmap.createBitmap(width, height,
                toCrop.getConfig() == null ? Bitmap.Config.ARGB_8888 : toCrop.getConfig());
    }
    Canvas canvas = new Canvas(result);
    Paint paint = new Paint(PAINT_FLAGS);
    canvas.drawBitmap(toCrop, m, paint);
    return result;
}

From source file:Main.java

public static Bitmap getFlippedBitmap(Resources res, int resId) {

    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;//from   www .ja va2  s  . c  o  m
    //Below line is necessary to fill in opt.outWidth, opt.outHeight
    Bitmap b = BitmapFactory.decodeResource(res, resId, opt);

    b = Bitmap.createBitmap(opt.outWidth, opt.outHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b);

    Matrix flipHorizontalMatrix = new Matrix();
    flipHorizontalMatrix.setScale(-1, 1);
    flipHorizontalMatrix.postTranslate(b.getWidth(), 0);

    Bitmap bb = BitmapFactory.decodeResource(res, resId);
    canvas.drawBitmap(bb, flipHorizontalMatrix, null);

    return b;
}

From source file:Main.java

public static Bitmap drawImageBorder(Bitmap srcBitmap, Bitmap borderBitmap) {
    if (srcBitmap == null)
        throw new NullPointerException("srcBitmap should not null");
    if (borderBitmap == null)
        return srcBitmap;
    Bitmap temp = srcBitmap.copy(Config.ARGB_8888, true);
    /*Bitmap border = borderBitmap;
    if (srcBitmap.getWidth() != borderBitmap.getWidth() || 
      srcBitmap.getHeight() != borderBitmap.getHeight()) {
       border = zoomBitmap(borderBitmap, srcBitmap.getWidth(), srcBitmap.getHeight());
    }*//*from ww  w.j  a  v a 2 s .  co  m*/
    Canvas canvas = new Canvas(temp);
    Matrix m = new Matrix();
    m.postScale((float) temp.getWidth() / borderBitmap.getWidth(),
            (float) temp.getHeight() / borderBitmap.getHeight());
    //canvas.drawBitmap(border, 0, 0, null);
    canvas.drawBitmap(borderBitmap, m, null);
    return temp;
}

From source file:Main.java

public static Bitmap getBitmap(Bitmap background, Bitmap contour, float alpha) {
    Paint paint = new Paint();
    paint.setAntiAlias(true);/*from w w  w  .  ja  v a2 s  .  c  om*/
    paint.setColor(Color.WHITE);
    paint.setDither(false);
    Bitmap bitmap = Bitmap.createBitmap(contour.getWidth(), contour.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Matrix m = new Matrix();
    m.setScale(contour.getWidth() * 1.0f / background.getWidth(),
            contour.getHeight() * 1.0f / background.getHeight());
    paint.setAlpha((int) (alpha * 0xff));
    canvas.drawBitmap(background, m, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
    paint.setAlpha(0xff);
    canvas.drawBitmap(contour, 0, 0, paint);
    return bitmap;
}

From source file:Main.java

public static void drawBitmapCenter(Canvas canvas, float f, float f1, float f2, boolean flag, boolean flag1,
        Bitmap bitmap, Paint paint) {
    if (flag) {/*from  w  ww  .ja v  a2s .  c  o  m*/
        f -= (f2 * (float) bitmap.getWidth()) / 2.0F;
    }
    if (flag1) {
        f1 -= (f2 * (float) bitmap.getHeight()) / 2.0F;
    }
    Matrix matrix = new Matrix();
    matrix.setScale(f2, f2);
    matrix.postTranslate(f, f1);
    canvas.drawBitmap(bitmap, matrix, paint);
}

From source file:Main.java

public static Bitmap scaleBitmap(Bitmap bitmap, int width, int height) {
    int newWidth = width;
    int newHeight = height;
    // if(newWidth < bitmap.getWidth()){
    // return bitmap;
    // }// w ww  .ja v a  2s . c om
    if (newHeight == 0) {
        newHeight = (int) (newWidth / (float) bitmap.getWidth() * bitmap.getHeight());
    }
    Bitmap result = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
    Canvas canvas = new Canvas(result);
    Matrix matrix = new Matrix();
    float scaleX = 1;
    float scaleY = 1;
    // if(newWidth>bitmap.getWidth()){
    scaleX = newWidth / (float) bitmap.getWidth();
    if (height != 0) {
        scaleY = newHeight / (float) bitmap.getHeight();
    } else {
        scaleY = scaleX;
    }
    // }
    matrix.postScale(scaleX, scaleY);
    canvas.drawBitmap(bitmap, matrix, null);
    return result;
}

From source file:Main.java

public static Bitmap createScaledBitmap(Bitmap bitmap, int width, int height) {
    Bitmap background = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
    float originalWidth = bitmap.getWidth(), originalHeight = bitmap.getHeight();
    Canvas canvas = new Canvas(background);
    float scale = Math.max(width / originalWidth, height / originalHeight);
    float xTranslation = 0.0f, yTranslation = (height - originalHeight * scale) / 2.0f;
    if (originalWidth < originalHeight) {
        // scale = height / originalHeight;
        xTranslation = (width - originalWidth * scale) / 2.0f;
        yTranslation = 0.0f;//w w w .ja v a 2s . co m
    }
    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);
    Paint paint = new Paint();
    paint.setFilterBitmap(true);
    canvas.drawBitmap(bitmap, transformation, paint);
    return background;
}

From source file:com.example.wojtekswiderski.woahpaper.GcmIntentService.java

public boolean setWallPaper(int start) {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

    String url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&q=" + word + "&start="
            + start;//w w w  .  j  a va  2  s.co m
    String imageUrl;
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject deliverable;

        try {
            deliverable = new JSONObject(response.toString());
            imageUrl = deliverable.getJSONObject("responseData").getJSONArray("results").getJSONObject(0)
                    .getString("url");
            Log.i(TAG, imageUrl);
            URL imageObj = new URL(imageUrl);

            Bitmap bmp = BitmapFactory.decodeStream(imageObj.openConnection().getInputStream());

            int x = bmp.getWidth();
            int y = bmp.getHeight();
            double ratioX = ((double) x) / ((double) width);
            double ratioY = ((double) y) / ((double) height);

            Log.i(TAG, "Width: " + width + " Height: " + height);
            Log.i(TAG, "X: " + x + " Y: " + y);
            Log.i(TAG, "RatioX: " + ratioX + " RatioY: " + ratioY);

            if (ratioX > ratioY) {
                bmp = Bitmap.createScaledBitmap(bmp, (int) (((double) x) / ratioY), height, false);
            } else {
                bmp = Bitmap.createScaledBitmap(bmp, width, (int) (((double) y) / ratioX), false);
            }

            Log.i(TAG, "newX: " + bmp.getWidth() + " newY: " + bmp.getHeight());

            Bitmap bmpBack = Bitmap.createBitmap(getWallpaperDesiredMinimumWidth(),
                    getWallpaperDesiredMinimumHeight(), Bitmap.Config.ARGB_8888);
            Bitmap bmOverlay = Bitmap.createBitmap(bmpBack.getWidth(), bmpBack.getHeight(),
                    bmpBack.getConfig());

            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmpBack, new Matrix(), null);
            canvas.drawBitmap(bmp, getWallpaperDesiredMinimumWidth() / 2 - bmp.getWidth() / 2, 0, null);

            WallpaperManager wpm = WallpaperManager.getInstance(this);
            wpm.setBitmap(bmOverlay);
        } catch (JSONException ex) {
            Log.e(TAG, "Could not convert to object");
            ex.printStackTrace();
            return true;
        }
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e(TAG, "Wrong url");
        return true;
    } catch (IOException ey) {
        ey.printStackTrace();
        Log.e(TAG, "Server down");
        return true;
    }
    return false;
}

From source file:com.frapim.windwatch.Notifier.java

public Bitmap createIcon(Context context, Wind wind) {
    Paint paint = new Paint();
    int color = wind.scale.getColor(context);
    paint.setColor(color);//from w  w w .  java2 s.com
    paint.setStyle(Style.FILL_AND_STROKE);
    Bitmap bitmap = Bitmap.createBitmap(mBigIconSize, mBigIconSize, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Bitmap backgroundBmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.turbine);
    Bitmap backgroundScaled = Bitmap.createScaledBitmap(backgroundBmp, mBigIconSize, mBigIconSize, false);
    canvas.drawBitmap(backgroundScaled, new Matrix(), new Paint());
    canvas.drawPath(getArrowPath(wind.degrees), paint);
    return bitmap;
}

From source file:com.f2prateek.dfg.core.GenerateFrameService.java

@Override
public void startingImage(Bitmap screenshot) {
    // Create the large notification icon
    int imageWidth = screenshot.getWidth();
    int imageHeight = screenshot.getHeight();
    int iconSize = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
    final int shortSide = imageWidth < imageHeight ? imageWidth : imageHeight;

    // Check for if config is null, http://crashes.to/s/dd0857c8648
    Bitmap preview = Bitmap.createBitmap(shortSide, shortSide,
            screenshot.getConfig() == null ? Bitmap.Config.ARGB_8888 : screenshot.getConfig());
    Canvas c = new Canvas(preview);
    Paint paint = new Paint();
    ColorMatrix desat = new ColorMatrix();
    desat.setSaturation(0.25f);/*  ww w  .j a  v  a2  s  .c  om*/
    paint.setColorFilter(new ColorMatrixColorFilter(desat));
    Matrix matrix = new Matrix();
    matrix.postTranslate((shortSide - imageWidth) / 2, (shortSide - imageHeight) / 2);
    c.drawBitmap(screenshot, matrix, paint);
    c.drawColor(0x40FFFFFF);

    Bitmap croppedIcon = Bitmap.createScaledBitmap(preview, iconSize, iconSize, true);

    Intent nullIntent = new Intent(this, MainActivity.class);
    nullIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationBuilder = new NotificationCompat.Builder(this)
            .setTicker(resources.getString(R.string.screenshot_saving_ticker))
            .setContentTitle(resources.getString(R.string.screenshot_saving_title))
            .setSmallIcon(R.drawable.ic_stat_app_notification)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(preview))
            .setContentIntent(PendingIntent.getActivity(this, 0, nullIntent, 0))
            .setWhen(System.currentTimeMillis()).setProgress(0, 0, true).setLargeIcon(croppedIcon);

    Notification n = notificationBuilder.build();
    n.flags |= Notification.FLAG_NO_CLEAR;
    notificationManager.notify(DFG_NOTIFICATION_ID, n);
}