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:com.pablog178.pdfcreator.android.PdfcreatorModule.java

private void generateImageFunction(HashMap args) {
    if (args.containsKey("fileName")) {
        Object fileName = args.get("fileName");
        if (fileName instanceof String) {
            this.fileName = (String) fileName;
            Log.i(PROXY_NAME, "fileName: " + this.fileName);
        }//from   w w w .ja  va 2  s.co m
    } else
        return;

    if (args.containsKey("view")) {
        Object viewObject = args.get("view");
        if (viewObject instanceof TiViewProxy) {
            TiViewProxy viewProxy = (TiViewProxy) viewObject;
            this.view = viewProxy.getOrCreateView();
            if (this.view == null) {
                Log.e(PROXY_NAME, "NO VIEW was created!!");
                return;
            }
            Log.i(PROXY_NAME, "view: " + this.view.toString());
        }
    } else
        return;

    TiBaseFile file = TiFileFactory.createTitaniumFile(this.fileName, true);
    Log.i(PROXY_NAME, "file full path: " + file.nativePath());
    try {
        final int PDF_WIDTH = 612;
        final int PDF_HEIGHT = 792;
        Resources appResources = app.getResources();
        OutputStream outputStream = file.getOutputStream();
        int viewWidth = 1600;
        int viewHeight = 1;

        WebView view = (WebView) this.view.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = 1300;
            }

            if (viewHeight <= 0) {
                viewHeight = 2300;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
        }

        Log.i(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.i(PROXY_NAME, "viewHeight: " + viewHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        float density = appResources.getDisplayMetrics().density;

        Canvas canvas = new Canvas(viewBitmap);
        Matrix matrix = new Matrix();

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);

        float scaleFactorWidth = 1 / ((float) viewWidth / (float) PDF_WIDTH);
        float scaleFactorHeight = 1 / ((float) viewHeight / (float) PDF_HEIGHT);

        Log.i(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.i(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        matrix.setScale(scaleFactorWidth, scaleFactorWidth);

        Bitmap imageBitmap = Bitmap.createBitmap(PDF_WIDTH, PDF_HEIGHT, Bitmap.Config.ARGB_8888);
        Canvas imageCanvas = new Canvas(imageBitmap);
        imageCanvas.drawBitmap(viewBitmap, matrix, null);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        sendCompleteEvent();

    } catch (Exception exception) {
        Log.e(PROXY_NAME, "Error: " + exception.toString());
        sendErrorEvent(exception.toString());
    }
}

From source file:com.mappn.gfan.ui.HomeTabActivity.java

private Bitmap drawText(DisplayMetrics dm, Resources res, Bitmap bm, int num) {
    final int height = bm.getScaledHeight(dm);
    final int width = bm.getScaledWidth(dm);
    Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(newBitmap);
    canvas.drawBitmap(bm, new Matrix(), new Paint());
    Paint textPainter = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPainter.setColor(res.getColor(R.color.tab_app_num));
    textPainter.setTextSize(dm.scaledDensity * 12);
    textPainter.setTypeface(Typeface.DEFAULT_BOLD);
    float textWidth = textPainter.measureText(String.valueOf(num)) / 2;
    canvas.drawText(String.valueOf(num), width / 2 - textWidth, height / 2 + (dm.scaledDensity * 6),
            textPainter);/*from w ww.  j  a v  a2s.  c o  m*/
    canvas.save();
    return newBitmap;
}

From source file:edu.cens.loci.ui.PlaceListActivity.java

private Bitmap overlay(Bitmap... bitmaps) {

    if (bitmaps[0].equals(null))
        return null;

    Bitmap bmOverlay = Bitmap.createBitmap(60, 60, Bitmap.Config.ARGB_4444);

    Canvas canvas = new Canvas(bmOverlay);
    for (int i = 0; i < bitmaps.length; i++)
        canvas.drawBitmap(bitmaps[i], new Matrix(), null);

    return bmOverlay;
}

From source file:bluetoothchat.BluetoothChatFragment.java

/**
 * overllay a tick on the underlaying sticker image
 * @param bmp1 sticker image/*from w  w  w. j  a  v  a  2 s. c o m*/
 * @return
 */
private Bitmap bitmapOverlay(Bitmap bmp1) {
    Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.accept2);
    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, new Matrix(), null);
    canvas.drawBitmap(bmp2, new Matrix(), null);
    return bmOverlay;
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

static void setBackground(View v, Bitmap bm) {

    if (bm == null) {
        v.setBackgroundResource(0);//from www.j  a v  a 2 s  .c  o  m
        return;
    }

    int vwidth = v.getWidth();
    int vheight = v.getHeight();
    int bwidth = bm.getWidth();
    int bheight = bm.getHeight();
    float scalex = (float) vwidth / bwidth;
    float scaley = (float) vheight / bheight;
    float scale = Math.max(scalex, scaley) * 1.3f;

    Bitmap.Config config = Bitmap.Config.ARGB_8888;
    Bitmap bg = Bitmap.createBitmap(vwidth, vheight, config);
    Canvas c = new Canvas(bg);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    ColorMatrix greymatrix = new ColorMatrix();
    greymatrix.setSaturation(0);
    ColorMatrix darkmatrix = new ColorMatrix();
    darkmatrix.setScale(.3f, .3f, .3f, 1.0f);
    greymatrix.postConcat(darkmatrix);
    ColorFilter filter = new ColorMatrixColorFilter(greymatrix);
    paint.setColorFilter(filter);
    Matrix matrix = new Matrix();
    matrix.setTranslate(-bwidth / 2, -bheight / 2); // move bitmap center to origin
    matrix.postRotate(10);
    matrix.postScale(scale, scale);
    matrix.postTranslate(vwidth / 2, vheight / 2); // Move bitmap center to view center
    c.drawBitmap(bm, matrix, paint);
    v.setBackgroundDrawable(new BitmapDrawable(bg));
}

From source file:com.abct.tljr.news.widget.ZoomableImageView.java

@Override
protected void onDraw(Canvas canvas) {
    // Check if the bitmap was ever set
    if (mBitmap != null && !mBitmap.isRecycled()) {

        // If the current version is above Gingerbread and the layer type is 
        // hardware accelerated, the paint is no longer needed

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
                && getLayerType() == View.LAYER_TYPE_HARDWARE) {
            canvas.drawBitmap(mBitmap, mMatrix, null);

        } else {/*from  w w w  .ja  va2  s.  c  o m*/
            // Check if the time between draws has been met and draw the bitmap
            if ((System.currentTimeMillis() - mLastDraw) > sPaintDelay) {
                canvas.drawBitmap(mBitmap, mMatrix, mPaint);
                mLastDraw = System.currentTimeMillis();
            }

            // Otherwise draw the bitmap without the paint and resubmit a new request
            else {
                canvas.drawBitmap(mBitmap, mMatrix, null);
                removeCallbacks(mRefresh);
                postDelayed(mRefresh, sPaintDelay);
            }
        }
    }
}

From source file:cn.jmessage.android.uikit.pickerimage.view.BaseZoomableImageView.java

@SuppressLint("NewApi")
@Override/*from   w w w  .  j av  a2  s  .  c  o m*/
protected void onDraw(Canvas canvas) {
    // Check if the bitmap was ever set
    if (mBitmap != null && !mBitmap.isRecycled()) {

        // If the current version is above Gingerbread and the layer type is 
        // hardware accelerated, the paint is no longer needed
        if (Build.VERSION.SDK_INT >= MIN_SDK_ENABLE_LAYER_TYPE_HARDWARE
                && getLayerType() == View.LAYER_TYPE_HARDWARE) {
            canvas.drawBitmap(mBitmap, mMatrix, null);
        } else {
            // Check if the time between draws has been met and draw the bitmap
            if ((System.currentTimeMillis() - mLastDraw) > sPaintDelay) {
                canvas.drawBitmap(mBitmap, mMatrix, mPaint);
                mLastDraw = System.currentTimeMillis();
            }

            // Otherwise draw the bitmap without the paint and resubmit a new request
            else {
                canvas.drawBitmap(mBitmap, mMatrix, null);
                removeCallbacks(mRefresh);
                postDelayed(mRefresh, sPaintDelay);
            }
        }
    }
}

From source file:com.scigames.registration.Registration4PhotoActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST) {
        or.setVisibility(View.VISIBLE);
        retakeButton.setVisibility(View.VISIBLE);
        saveButton.setVisibility(View.VISIBLE);
        takePhotoButton.setVisibility(View.INVISIBLE);

        if (data.hasExtra("data")) {
            //change to new view
            photo = (Bitmap) data.getExtras().get("data");
            //photoUri = data.getExtras().get("data");
            Log.d(TAG, "photoDensity: ");
            Log.d(TAG, String.valueOf(photo.getDensity()));
            Log.d(TAG, "photo getHeight:");
            Log.d(TAG, String.valueOf(photo.getHeight()));
            Log.d(TAG, "photo getWidth");
            Log.d(TAG, String.valueOf(photo.getWidth()));
            Log.d(TAG, "photo config:");
            if (photo.getHeight() < photo.getWidth()) {
                Log.d(TAG, "height < width");

                Log.d(TAG, photo.getConfig().toString());
                photoToSend = Bitmap.createBitmap(120, 160, photo.getConfig());
                //photoToSend = Bitmap.createBitmap(photo);
                Canvas canvas = new Canvas(photoToSend);
                Log.d(TAG, "photo getScaledHeight:");
                Log.d(TAG, String.valueOf(photo.getScaledHeight(canvas)));
                Log.d(TAG, "photo getScaledWidth");
                Log.d(TAG, String.valueOf(photo.getScaledWidth(canvas)));
                Matrix matrix = new Matrix();
                //matrix.preScale(-1.0f, 1.0f);
                //Bitmap mirroredBitmap = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight());
                matrix.setRotate(270, photo.getWidth() / 2, photo.getHeight() / 2);

                //matrix.postTranslate(photo.getWidth(),photo.getHeight());
                Log.d(TAG, matrix.toString());
                canvas.drawBitmap(photo, matrix, new Paint());
            } else {
                Log.d(TAG, photo.getConfig().toString());
                photoToSend = Bitmap.createBitmap(120, 160, photo.getConfig());
                //photoToSend = Bitmap.createBitmap(photo); 
                Canvas canvas = new Canvas(photoToSend);
                Log.d(TAG, "photo getScaledHeight:");
                Log.d(TAG, String.valueOf(photo.getScaledHeight(canvas)));
                Log.d(TAG, "photo getScaledWidth");
                Log.d(TAG, String.valueOf(photo.getScaledWidth(canvas)));
                Matrix matrix = new Matrix();
                //matrix.preScale(-1.0f, 1.0f);
                //Bitmap mirroredBitmap = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight());
                //matrix.setRotate(0, photo.getWidth()/2, photo.getHeight()/2);
                //matrix.setScale(0.9f, 0.9f);
                Log.d(TAG, matrix.toString());
                //matrix.postTranslate(photo.getWidth(),photo.getHeight());

                canvas.drawBitmap(photo, matrix, new Paint());
                avatarPhoto.setScaleX(0.95f);
                avatarPhoto.setScaleY(0.95f);
                avatarPhoto.setX(180f);//from w  w w.  j ava2s. c om
                avatarPhoto.setY(440f);
            }
            avatarPhoto.setImageBitmap(photoToSend);

            Log.d(TAG, "photoToSendDensity: ");
            Log.d(TAG, String.valueOf(photoToSend.getDensity()));
            Log.d(TAG, "photoToSend getScaledHeight:");
            Log.d(TAG, String.valueOf(photoToSend.getHeight()));
            Log.d(TAG, "photoToSend getScaledWidth");
            Log.d(TAG, String.valueOf(photoToSend.getWidth()));
        } else {
            or.setVisibility(View.INVISIBLE);
            saveButton.setVisibility(View.INVISIBLE);
            retakeButton.setVisibility(View.INVISIBLE);
            takePhotoButton.setVisibility(View.VISIBLE);
            //instruction.setText("");
        }
    }
}

From source file:com.ddoskify.CameraOverlayActivity.java

/**
 * Initializes the UI and initiates the creation of a face detector.
 */// ww w . j  av a  2s.  c o  m
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
    mFaces = new ArrayList<FaceTracker>();

    final ImageButton button = (ImageButton) findViewById(R.id.flipButton);
    button.setOnClickListener(mFlipButtonListener);

    if (savedInstanceState != null) {
        mIsFrontFacing = savedInstanceState.getBoolean("IsFrontFacing");
    }

    mTakePictureButton = (Button) findViewById(R.id.takePictureButton);
    mTakePictureButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.e("CameraOverlay", "Button has been pressed");
            mCameraSource.takePicture(new CameraSource.ShutterCallback() {
                @Override
                public void onShutter() {
                    //                        mCameraSource.stop();
                    Snackbar.make(findViewById(android.R.id.content), "Picture Taken!", Snackbar.LENGTH_SHORT)
                            .setActionTextColor(Color.BLACK).show();
                }
            }, new CameraSource.PictureCallback() {
                public void onPictureTaken(byte[] data) {
                    int re = ActivityCompat.checkSelfPermission(getApplicationContext(),
                            Manifest.permission.WRITE_EXTERNAL_STORAGE);

                    if (!isStorageAllowed()) {
                        requestStoragePermission();
                    }

                    File pictureFile = getOutputMediaFile();
                    if (pictureFile == null) {
                        return;
                    }
                    try {

                        Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
                        Bitmap resizedBitmap = Bitmap.createBitmap(mGraphicOverlay.getWidth(),
                                mGraphicOverlay.getHeight(), picture.getConfig());
                        Canvas canvas = new Canvas(resizedBitmap);

                        Matrix matrix = new Matrix();

                        matrix.setScale((float) resizedBitmap.getWidth() / (float) picture.getWidth(),
                                (float) resizedBitmap.getHeight() / (float) picture.getHeight());

                        if (mIsFrontFacing) {
                            // mirror by inverting scale and translating
                            matrix.preScale(-1, 1);
                            matrix.postTranslate(canvas.getWidth(), 0);
                        }
                        Paint paint = new Paint();
                        canvas.drawBitmap(picture, matrix, paint);

                        mGraphicOverlay.draw(canvas); // make those accessible

                        FileOutputStream fos = new FileOutputStream(pictureFile);
                        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                        fos.close();

                        Intent intent = new Intent(getApplicationContext(), PhotoReviewActivity.class);
                        intent.putExtra(BITMAP_MESSAGE, pictureFile.toString());
                        startActivity(intent);
                        Log.d("CameraOverlay", "Starting PhotoReviewActivity " + pictureFile.toString());

                    } catch (FileNotFoundException e) {
                        Log.e("CameraOverlay", e.toString());
                    } catch (IOException e) {
                        Log.e("CameraOverlay", e.toString());
                    }
                }
            });
        }
    });

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource();
    } else {
        requestCameraPermission();
    }
}

From source file:com.dynamixsoftware.printingsample.IntentApiFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.check_premium:
        new AlertDialog.Builder(requireContext()).setTitle(R.string.check_premium)
                .setMessage("" + intentApi.checkPremium()).setPositiveButton(R.string.ok, null).show();
        break;/*from w w w .java 2  s .  c o m*/
    case R.id.activate_online:
        final Context appContext = requireContext().getApplicationContext();
        intentApi.setLicense("YOUR_ACTIVATION_KEY", new ISetLicenseCallback.Stub() {
            @Override
            public void start() {
                toastInMainThread(appContext, "activate start");
            }

            @Override
            public void serverCheck() {
                toastInMainThread(appContext, "activate check server");
            }

            @Override
            public void finish(final Result arg0) {
                toastInMainThread(appContext, "activate finish " + (arg0 == Result.OK ? "ok" : "error"));
            }
        });
        break;
    case R.id.setup_printer:
        intentApi.setupCurrentPrinter();
        break;
    case R.id.change_options:
        intentApi.changePrinterOptions();
        break;
    case R.id.get_current_printer:
        try {
            IPrinterInfo printer = intentApi.getCurrentPrinter();
            Toast.makeText(requireContext().getApplicationContext(),
                    "current printer " + (printer != null ? printer.getName() : "null"), Toast.LENGTH_LONG)
                    .show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image:
        intentApi.print(Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                "image/png", "from printing sample");
        break;
    case R.id.print_file:
        intentApi.print(Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)),
                "application/msword", "from printing sample");
        break;
    case R.id.show_file_preview:
        intentApi.showFilePreview(
                Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)),
                "application/msword", 0);
        break;
    case R.id.print_with_your_rendering:
        try {
            IDocument.Stub document = new IDocument.Stub() {

                private int thumbnailWidth;
                private int thumbnailHeight;

                @Override
                public Bitmap renderPageFragment(int arg0, Rect fragment) throws RemoteException {
                    IPrinterInfo printer = intentApi.getCurrentPrinter();
                    if (printer != null) {
                        Bitmap bitmap = Bitmap.createBitmap(fragment.width(), fragment.height(),
                                Bitmap.Config.ARGB_8888);
                        for (int i = 0; i < 3; i++)
                            try {
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                options.inDither = false;
                                if (i > 0) {
                                    options.inSampleSize = 1 << i;
                                }
                                Bitmap imageBMP = BitmapFactory.decodeStream(
                                        new FileInputStream(
                                                FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                        null, options);
                                Paint p = new Paint();
                                int imageWidth = 0;
                                int imageHeight = 0;
                                if (imageBMP != null) {
                                    imageWidth = imageBMP.getWidth();
                                    imageHeight = imageBMP.getHeight();
                                }
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                int paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                int paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                                float aspectH = (float) imageHeight / (float) paperHeight;
                                float aspectW = (float) imageWidth / (float) paperWidth;
                                aspectH = aspectH > 1 ? 1 / aspectH : aspectH;
                                aspectW = aspectW > 1 ? 1 / aspectW : aspectW;
                                RectF dst = new RectF(0, 0, fragment.width() * aspectW,
                                        fragment.height() * aspectH);
                                float sLeft = 0;
                                float sTop = fragment.top * aspectH;
                                float sRight = imageWidth;
                                float sBottom = fragment.top * aspectH + fragment.bottom * aspectH;
                                RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                                Canvas canvas = new Canvas(bitmap);
                                canvas.drawColor(Color.WHITE);
                                // move image to actual printing area
                                dst.offsetTo(dst.left - fragment.left, dst.top - fragment.top);
                                Matrix matrix = new Matrix();
                                matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                                canvas.drawBitmap(imageBMP, matrix, p);
                                break;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                break;
                            } catch (OutOfMemoryError ex) {
                                if (bitmap != null) {
                                    bitmap.recycle();
                                    bitmap = null;
                                }
                                continue;
                            }
                        return bitmap;
                    } else {
                        return null;
                    }
                }

                @Override
                public void initDeviceContext(IPrinterContext printerContext, int thumbnailWidth,
                        int thumbnailHeight) {
                    this.thumbnailWidth = thumbnailWidth;
                    this.thumbnailHeight = thumbnailHeight;
                }

                @Override
                public int getTotalPages() {
                    return 1;
                }

                @Override
                public String getDescription() {
                    return "PrintHand test page";
                }

                @Override
                public Bitmap getPageThumbnail(int arg0) throws RemoteException {
                    Bitmap bitmap = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight,
                            Bitmap.Config.ARGB_8888);
                    for (int i = 0; i < 3; i++)
                        try {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                            options.inDither = false;
                            if (i > 0) {
                                options.inSampleSize = 1 << i;
                            }
                            Bitmap imageBMP = BitmapFactory.decodeStream(
                                    new FileInputStream(
                                            FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                    null, options);
                            Paint p = new Paint();
                            int imageWidth = 0;
                            int imageHeight = 0;
                            if (imageBMP != null) {
                                imageWidth = imageBMP.getWidth();
                                imageHeight = imageBMP.getHeight();
                            }
                            // default
                            int paperWidth = 2481;
                            int paperHeight = 3507;
                            IPrinterInfo printer = intentApi.getCurrentPrinter();
                            if (printer != null) {
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                            }
                            float aspectW = (float) imageWidth / (float) paperWidth;
                            float aspectH = (float) imageHeight / (float) paperHeight;
                            RectF dst = new RectF(0, 0, thumbnailWidth * aspectW, thumbnailHeight * aspectH);
                            float sLeft = 0;
                            float sTop = 0;
                            float sRight = imageWidth;
                            float sBottom = imageHeight;
                            RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                            Canvas canvas = new Canvas(bitmap);
                            canvas.drawColor(Color.WHITE);
                            Matrix matrix = new Matrix();
                            matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                            canvas.drawBitmap(imageBMP, matrix, p);
                            break;
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            break;
                        } catch (OutOfMemoryError ex) {
                            if (bitmap != null) {
                                bitmap.recycle();
                                bitmap = null;
                            }
                            continue;
                        }
                    return bitmap;
                }
            };
            intentApi.print(document);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_with_your_rendering_without_ui:
        try {
            IJob.Stub job = new IJob.Stub() {
                @Override
                public Bitmap renderPageFragment(int num, Rect fragment) throws RemoteException {
                    IPrinterInfo printer = intentApi.getCurrentPrinter();
                    if (printer != null) {
                        Bitmap bitmap = Bitmap.createBitmap(fragment.width(), fragment.height(),
                                Bitmap.Config.ARGB_8888);
                        for (int i = 0; i < 3; i++)
                            try {
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                options.inDither = false;
                                if (i > 0) {
                                    options.inSampleSize = 1 << i;
                                }
                                Bitmap imageBMP = BitmapFactory.decodeStream(
                                        new FileInputStream(
                                                FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)),
                                        null, options);
                                Paint p = new Paint();
                                int imageWidth = 0;
                                int imageHeight = 0;
                                if (imageBMP != null) {
                                    imageWidth = imageBMP.getWidth();
                                    imageHeight = imageBMP.getHeight();
                                }
                                int xDpi = printer.getPrinterContext().getHResolution();
                                int yDpi = printer.getPrinterContext().getVResolution();
                                // in dots
                                int paperWidth = printer.getPrinterContext().getPaperWidth() * xDpi / 72;
                                int paperHeight = printer.getPrinterContext().getPaperHeight() * yDpi / 72;
                                float aspectH = (float) imageHeight / (float) paperHeight;
                                float aspectW = (float) imageWidth / (float) paperWidth;
                                RectF dst = new RectF(0, 0, fragment.width() * aspectW,
                                        fragment.height() * aspectH);
                                float sLeft = 0;
                                float sTop = fragment.top * aspectH;
                                float sRight = imageWidth;
                                float sBottom = fragment.top * aspectH + fragment.bottom * aspectH;
                                RectF source = new RectF(sLeft, sTop, sRight, sBottom);
                                Canvas canvas = new Canvas(bitmap);
                                canvas.drawColor(Color.WHITE);
                                // move image to actual printing area
                                dst.offsetTo(dst.left - fragment.left, dst.top - fragment.top);
                                Matrix matrix = new Matrix();
                                matrix.setRectToRect(source, dst, Matrix.ScaleToFit.FILL);
                                canvas.drawBitmap(imageBMP, matrix, p);
                                break;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                break;
                            } catch (OutOfMemoryError ex) {
                                if (bitmap != null) {
                                    bitmap.recycle();
                                    bitmap = null;
                                }
                                continue;
                            }
                        return bitmap;
                    } else {
                        return null;
                    }
                }

                @Override
                public int getTotalPages() {
                    return 1;
                }
            };
            intentApi.print(job, 1);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "image/png",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PNG)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.change_image_options:
        try {
            List<PrintHandOption> imageOptions = intentApi.getImagesOptions();
            changeRandomOption(imageOptions);
            intentApi.setImagesOptions(imageOptions);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_file_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "application/ms-word",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_DOC)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_protected_file_with_print_hand_rendering_without_ui:
        try {
            intentApi.print("PrintingSample", "application/pdf",
                    Uri.parse("file://" + FilesUtils.getFilePath(requireContext(), FilesUtils.FILE_PDF)));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.change_files_options:
        try {
            List<PrintHandOption> fileOptions = intentApi.getFilesOptions();
            changeRandomOption(fileOptions);
            intentApi.setFilesOptions(fileOptions);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    }
}