Example usage for android.graphics Canvas drawColor

List of usage examples for android.graphics Canvas drawColor

Introduction

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

Prototype

public void drawColor(@ColorInt int color) 

Source Link

Document

Fill the entire canvas' bitmap (restricted to the current clip) with the specified color, using srcover porterduff mode.

Usage

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;// w  ww  .  jav  a 2s.  co  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;
    }
}

From source file:com.cloverstudio.spika.CameraCropActivity.java

/**
 * Get the image from container - it is already cropped and zoomed If the
 * image is smaller than container it will be black color set aside
 * *///  w  ww  .j ava2s  .c o m
private Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(crop_container_size, crop_container_size,
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.BLACK);
    view.draw(canvas);
    return returnedBitmap;
}

From source file:com.example.ysh.myapplication.view.readview.PageFactory.java

/**
 * ?//from ww w. j  av  a2 s.co m
 *
 * @param canvas
 */
public synchronized void onDraw(Canvas canvas) {
    if (mLines.size() == 0) {
        curEndPos = curBeginPos;
        mLines = pageDown();
    }
    if (mLines.size() > 0) {
        int y = marginHeight + (mLineSpace << 1);
        // 
        if (mBookPageBg != null) {
            canvas.drawBitmap(mBookPageBg, null, rectF, null);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        // 
        canvas.drawText(chaptersList.get(currentChapter - 1).title, marginWidth, y, mTitlePaint);
        y += mLineSpace + mNumFontSize;
        // ?
        for (String line : mLines) {
            y += mLineSpace;
            if (line.endsWith("@")) {
                canvas.drawText(line.substring(0, line.length() - 1), marginWidth, y, mPaint);
                y += mLineSpace;
            } else {
                canvas.drawText(line, marginWidth, y, mPaint);
            }
            y += mFontSize;
        }
        // ??
        if (batteryBitmap != null) {
            canvas.drawBitmap(batteryBitmap, marginWidth + 2,
                    mHeight - marginHeight - ScreenUtils.dpToPxInt(12), mTitlePaint);
        }

        float percent = (float) currentChapter * 100 / chapterSize;
        canvas.drawText(decimalFormat.format(percent) + "%", (mWidth - percentLen) / 2, mHeight - marginHeight,
                mTitlePaint);

        String mTime = dateFormat.format(new Date());
        canvas.drawText(mTime, mWidth - marginWidth - timeLen, mHeight - marginHeight, mTitlePaint);

        // ?
        SettingManager.getInstance().saveReadProgress(bookId, currentChapter, curBeginPos, curEndPos);
    }
}

From source file:com.android.systemui.statusbar.phone.NavigationBarView.java

private void updateColor(boolean defaults) {
    Bitmap bm = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    Canvas cnv = new Canvas(bm);

    if (defaults) {
        cnv.drawColor(0xFF000000);
        setBackground(new BitmapDrawable(bm));
        return;//from   w  w  w.  jav a  2s  .c  o  m
    }

    String setting = Settings.System.getString(mContext.getContentResolver(), Settings.System.NAV_BAR_COLOR);
    String[] colors = (setting == null || setting.equals("")
            ? ExtendedPropertiesUtils.PARANOID_COLORS_DEFAULTS[ExtendedPropertiesUtils.PARANOID_COLORS_NAVBAR]
            : setting).split(ExtendedPropertiesUtils.PARANOID_STRING_DELIMITER);
    String currentColor = colors[Integer.parseInt(colors[2])];

    cnv.drawColor(new BigInteger(currentColor, 16).intValue());

    TransitionDrawable transition = new TransitionDrawable(
            new Drawable[] { getBackground(), new BitmapDrawable(bm) });
    transition.setCrossFadeEnabled(true);
    setBackground(transition);
    transition.startTransition(1000);
}

From source file:com.apache.fastandroid.novel.view.readview.PageFactory.java

/**
 * ?/*ww  w  . j  a va  2 s.  c  o  m*/
 *
 * @param canvas
 */
public synchronized void onDraw(Canvas canvas) {
    if (mLines.size() == 0) {
        curEndPos = curBeginPos;
        mLines = pageDown();
    }
    if (mLines.size() > 0) {
        int y = marginHeight + (mLineSpace << 1);
        // 
        if (mBookPageBg != null) {
            canvas.drawBitmap(mBookPageBg, null, rectF, null);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        // 
        canvas.drawText(chaptersList.get(currentChapter - 1).title, marginWidth, y, mTitlePaint);
        y += mLineSpace + mNumFontSize;
        // ?
        for (String line : mLines) {
            y += mLineSpace;
            if (line.endsWith("@")) {
                canvas.drawText(line.substring(0, line.length() - 1), marginWidth, y, mPaint);
                y += mLineSpace;
            } else {
                canvas.drawText(line, marginWidth, y, mPaint);
            }
            y += mFontSize;
        }
        // ??
        if (batteryBitmap != null) {
            canvas.drawBitmap(batteryBitmap, marginWidth + 2,
                    mHeight - marginHeight - DimensUtil.dp2px(mContext, 12), mTitlePaint);
        }

        float percent = (float) currentChapter * 100 / chapterSize;
        canvas.drawText(decimalFormat.format(percent) + "%", (mWidth - percentLen) / 2, mHeight - marginHeight,
                mTitlePaint);

        String mTime = dateFormat.format(new Date());
        canvas.drawText(mTime, mWidth - marginWidth - timeLen, mHeight - marginHeight, mTitlePaint);

        // ?
        SettingManager.getInstance().saveReadProgress(bookId, currentChapter, curBeginPos, curEndPos);
    }
}

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

@Override
public void onClick(View v) {
    final Context appContext = requireContext().getApplicationContext();
    switch (v.getId()) {
    case R.id.set_license:
        printingSdk.setLicense("YOUR_LICENSE_HERE", new ISetLicenseCallback.Stub() {
            @Override/*from  w w w  .  j a  v a 2s . c om*/
            public void start() {
                Toast.makeText(appContext, "set license start", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void serverCheck() {
                Toast.makeText(appContext, "set license check server", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void finish(Result result) {
                Toast.makeText(appContext, "set license finish " + (result == Result.OK ? "ok" : "error"),
                        Toast.LENGTH_SHORT).show();
            }
        });
        break;
    case R.id.init_current_and_recent_printers:
        try {
            printingSdk.initRecentPrinters(new ISetupPrinterListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "ISetupPrinterListener start");
                }

                @Override
                public void libraryPackInstallationProcess(int arg0) {
                    toastInMainThread(appContext,
                            "ISetupPrinterListener libraryPackInstallationProcess " + arg0 + " %");
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "ISetupPrinterListener finish " + arg0.name());
                    if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                        // printingSdk.setup should be called with forceInstall = true to download required drivers
                    }
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.get_current_printer:
        try {
            Printer currentPrinter = printingSdk.getCurrentPrinter();
            showDialog(getString(R.string.success),
                    "Current printer:\n" + (currentPrinter != null ? currentPrinter.getName() : "null"));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.get_recent_printers:
        try {
            List<Printer> recentPrinters = printingSdk.getRecentPrintersList();
            String message = "";
            for (Printer printer : recentPrinters)
                message += printer.getName() + "\n";
            if (message.length() == 0)
                message = "No recent printers";
            showDialog(getString(R.string.success), message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_wifi:
        try {
            printingSdk.startDiscoverWiFi(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_bluetooth:
        try {
            printingSdk.startDiscoverBluetooth(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_google_cloud:
        try {
            printingSdk.startDiscoverCloud("YOUR_GOOGLE_ACCOUNT_NAME", new IDiscoverCloudListener.Stub() {

                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverCloudListener start");
                }

                @Override
                public void showAuthorization(Intent arg0) {
                    // Launch Intent arg0 to show authorization activity
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverCloudListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverCloudListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_smb:
        try {
            discoverSmb = printingSdk.startDiscoverSmb(new IDiscoverSmbListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverSmbListener start");
                }

                @Override
                public void smbFilesFound(List<SmbFile> arg0) {
                    // Show list of SMB files. This listener is used for navigation.
                    // You should call discoverSmbControl.move(arg0) to change location.
                }

                @Override
                public void showAuthorization() {
                    // You have to ask user for authorization credentials and call discoverSmbControl.login(arg0, arg1);
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverSmbListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverSmbListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.discover_usb:
        try {
            printingSdk.startDiscoverUSB(new IDiscoverListener.Stub() {
                @Override
                public void start() {
                    toastInMainThread(appContext, "IDiscoverListener start");
                }

                @Override
                public void printerFound(List<Printer> arg0) {
                    toastInMainThread(appContext, "IDiscoverListener printerFound");
                    discoveredPrinters.clear();
                    discoveredPrinters.addAll(arg0);
                }

                @Override
                public void finish(Result arg0) {
                    toastInMainThread(appContext, "IDiscoverListener finish " + arg0.name());
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.find_driver:
        if (!discoveredPrinters.isEmpty()) {
            Printer printer = discoveredPrinters.get(0);
            try {
                printingSdk.findDrivers(printer, new IFindDriversListener.Stub() {
                    @Override
                    public void start() {
                        toastInMainThread(appContext, "IFindDriversListener start");
                    }

                    @Override
                    public void finish(List<DriversSearchEntry> arg0) {
                        toastInMainThread(appContext, "IFindDriversListener finish; Found " + arg0.size()
                                + " drivers entries;" + ((arg0.size() == 0) ? "" : ""));
                        driversSearchEntries.clear();
                        driversSearchEntries.addAll(arg0);
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.get_drivers:
        if (!discoveredPrinters.isEmpty()) {
            Printer printer = discoveredPrinters.get(0);
            TransportType transportType = printer.getTransportTypes().get(0);
            if (transportType != null) {
                try {
                    printingSdk.getDriversList(printer, transportType, new IGetDriversListener.Stub() {
                        @Override
                        public void start() {
                            toastInMainThread(appContext, "IGetDriversListener start");
                        }

                        @Override
                        public void finish(List<DriverHandleEntry> arg0) {
                            toastInMainThread(appContext, "IGetDriversListener finish");
                            driverHandleEntries.clear();
                            driverHandleEntries.addAll(arg0);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.setup_recent_printer:
        try {
            List<Printer> printerList = printingSdk.getRecentPrintersList();
            if (!printerList.isEmpty())
                printingSdk.setup(printerList.get(0), true, new ISetupPrinterListener.Stub() {
                    @Override
                    public void start() {
                        toastInMainThread(appContext, "ISetupPrinterListener start");
                    }

                    @Override
                    public void libraryPackInstallationProcess(int arg0) {
                        toastInMainThread(appContext,
                                "ISetupPrinterListener libraryPackInstallationProcess " + arg0 + " %");
                    }

                    @Override
                    public void finish(Result arg0) {
                        toastInMainThread(appContext, "ISetupPrinterListener finish " + arg0.name());
                        if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                            // printingSdk.setup should be called with forceInstall = true to download required drivers
                        }
                    }
                });
            else
                showDialog(getString(R.string.error), "No recent printers");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.setup_discovered_printer:
        if (!discoveredPrinters.isEmpty()) {
            if (!driversSearchEntries.isEmpty()) {
                Printer printer = discoveredPrinters.get(0);
                DriversSearchEntry driversSearchEntry = driversSearchEntries.get(0);
                try {
                    printingSdk.setup(printer, driversSearchEntry.getDriverHandlesList().get(0),
                            driversSearchEntry.getTransportType(), false, new ISetupPrinterListener.Stub() {
                                @Override
                                public void start() {
                                    toastInMainThread(appContext, "ISetupPrinterListener start");
                                }

                                @Override
                                public void libraryPackInstallationProcess(int arg0) {
                                    toastInMainThread(appContext,
                                            "ISetupPrinterListener libraryPackInstallationProcess " + arg0
                                                    + " %");
                                }

                                @Override
                                public void finish(Result arg0) {
                                    toastInMainThread(appContext,
                                            "ISetupPrinterListener finish " + arg0.name());
                                    if (arg0.getType().equals(ResultType.ERROR_LIBRARY_PACK_NOT_INSTALLED)) {
                                        // printingSdk.setup should be called with forceInstall = true to download required drivers
                                    }
                                }
                            });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(getString(R.string.error), "Find driver first");
        } else
            showDialog(getString(R.string.error), "Discover printers first");
        break;
    case R.id.change_options:
        try {
            Printer currentPrinter = printingSdk.getCurrentPrinter();
            if (currentPrinter != null) {
                List<PrinterOption> options = currentPrinter.getOptions();
                if (options.size() > 0) {
                    Random random = new Random();
                    PrinterOption option = options.get(random.nextInt(options.size()));
                    PrinterOptionValue currentValue = option.getOptionValue();
                    List<PrinterOptionValue> valuesList = option.getOptionValueList();
                    PrinterOptionValue newValue = valuesList.get(random.nextInt(valuesList.size()));
                    printingSdk.setCurrentPrinterOptionValue(option, newValue);
                    Toast.makeText(requireContext().getApplicationContext(),
                            "option " + option.getName() + " changed from " + currentValue + " to " + newValue,
                            Toast.LENGTH_LONG).show();
                }
            } else
                showDialog(getString(R.string.error), "Setup printer first");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    case R.id.print_image:
        try {
            if (printingSdk.getCurrentPrinter() != null) {
                List<IPage> pages = new ArrayList<>();
                pages.add(new IPage() {
                    @Override
                    public Bitmap getBitmapFragment(Rect fragment) {
                        Printer printer = null;
                        try {
                            printer = printingSdk.getCurrentPrinter();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        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.getContext().getHResolution();
                                    int yDpi = printer.getContext().getVResolution();
                                    // in dots
                                    int paperWidth = printer.getContext().getPaperWidth() * xDpi / 72;
                                    int paperHeight = printer.getContext().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;
                    }
                });
                try {
                    printingSdk.print(pages, 1, new IPrintListener.Stub() {
                        @Override
                        public void startingPrintJob() {
                            toastInMainThread(appContext, "IPrintListener startingPrintJob");
                        }

                        @Override
                        public void start() {
                            toastInMainThread(appContext, "IPrintListener start");
                        }

                        @Override
                        public void sendingPage(int arg0, int arg1) {
                            toastInMainThread(appContext,
                                    "IPrintListener sendingPage " + arg0 + "; progress " + arg1 + "%");
                        }

                        @Override
                        public void preparePage(int arg0) {
                            toastInMainThread(appContext, "IPrintListener preparePage " + arg0);
                        }

                        @Override
                        public boolean needCancel() {
                            toastInMainThread(appContext, "IPrintListener needCancel");
                            // Return false if cancel needed.
                            return false;
                        }

                        @Override
                        public void finishingPrintJob() {
                            toastInMainThread(appContext, "IPrintListener finishingPrintJob");

                        }

                        @Override
                        public void finish(Result arg0, int arg1, int arg2) {
                            toastInMainThread(appContext,
                                    "IPrintListener finish Result " + arg0 + "; Result type " + arg0.getType()
                                            + "; Total pages " + arg1 + "; Pages sent " + arg2);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(getString(R.string.error), "You must setup printer before print");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        break;
    }
}

From source file:com.achep.acdisplay.ui.widgets.CircleView.java

@Override
protected void onDraw(Canvas canvas) {
    final float ratio = calculateRatio();

    // Draw all corners
    drawCornerIcon(canvas, mDrawableLeftTopCorner, 0, 0 /* left top */);
    drawCornerIcon(canvas, mDrawableRightTopCorner, 1, 0 /* right top */);
    drawCornerIcon(canvas, mDrawableLeftBottomCorner, 0, 1 /* left bottom */);
    drawCornerIcon(canvas, mDrawableRightBottomCorner, 1, 1 /* right bottom */);

    // Darkening background
    int alpha = (int) (mDarkening * 255);
    alpha += (int) ((255 - alpha) * ratio * 0.7f); // Change alpha dynamically
    canvas.drawColor(
            Color.argb(alpha, Color.red(mOuterColor), Color.green(mOuterColor), Color.blue(mOuterColor)));

    // Draw unlock circle
    mPaint.setColor(mInnerColor);/*from   w  w  w  . j a  v  a 2s .co m*/
    mPaint.setAlpha((int) (255 * Math.pow(ratio, 1f / 3f)));
    canvas.drawCircle(mPoint[0], mPoint[1], mRadiusDrawn, mPaint);

    if (ratio >= 0.5f) {
        // Draw unlock icon at the center of circle
        float scale = 0.5f + 0.5f * ratio;
        canvas.save();
        canvas.translate(mPoint[0] - mDrawable.getMinimumWidth() / 2 * scale,
                mPoint[1] - mDrawable.getMinimumHeight() / 2 * scale);
        canvas.scale(scale, scale);
        mDrawable.draw(canvas);
        canvas.restore();
    }
}

From source file:app.newbee.lib.swipeback.SwipeBackLayout.java

private void drawScrim(Canvas canvas, View child) {
    final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
    final int alpha = (int) (baseAlpha * mScrimOpacity);
    final int color = alpha << 24 | (mScrimColor & 0xffffff);

    if ((mTrackingEdge & EDGE_LEFT) != 0) {
        canvas.clipRect(0, 0, child.getLeft(), getHeight());
    } else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
        canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
    } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
        canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
    }/*from w w  w .j  av  a  2s.com*/
    canvas.drawColor(color);
}

From source file:com.example.administrator.common.widget.swipeback.SwipeBackLayout.java

private void drawScrim(Canvas canvas, View child) {
    final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
    final int alpha = (int) (baseAlpha * mScrimOpacity);
    final int color = alpha << 24 | (mScrimColor & 0xffffff);

    if ((mTrackingEdge & EDGE_LEFT) != 0) {
        canvas.clipRect(0, 0, child.getLeft(), getHeight());
    } else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
        canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
    } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
        canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
    } else if ((mTrackingEdge & EDGE_TOP) != 0) {
        canvas.clipRect(0, child.getTop(), 0, getHeight());
    }/*  w w  w  . j av  a 2s  .  c  o m*/
    canvas.drawColor(color);
}

From source file:com.mylikes.likes.etchasketch.Slate.java

public Bitmap copyBitmap(boolean withBackground) {
    Bitmap newb = null;//from w ww . j a  v a  2  s.  c om
    Bitmap b = getBitmap();
    if (b != null) {
        newb = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
    }
    if (newb != null) {
        Canvas newc = new Canvas(newb);
        if (mBackgroundColor != Color.TRANSPARENT && withBackground) {
            newc.drawColor(mBackgroundColor);
        }
        newc.drawBitmap(b, 0, 0, null);
    }
    return newb;
}