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.android.gallery3d.filtershow.imageshow.ImageShow.java

private void drawHighresImage(Canvas canvas, Bitmap fullHighres) {
    Matrix originalToScreen = MasterImage.getImage().originalImageToScreen();
    if (fullHighres != null && originalToScreen != null) {
        Matrix screenToOriginal = new Matrix();
        originalToScreen.invert(screenToOriginal);
        Rect rBounds = new Rect();
        rBounds.set(MasterImage.getImage().getPartialBounds());
        if (fullHighres != null) {
            originalToScreen.preTranslate(rBounds.left, rBounds.top);
            canvas.clipRect(mImageBounds);
            canvas.drawBitmap(fullHighres, originalToScreen, mPaint);
        }//from  www .ja  v  a2 s. c  o m
    }
}

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//ww w .j a va  2  s. c o m
            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.abslyon.abetterselection.CoverFlow.CoverFlowView.java

protected final void drawChild(Canvas canvas, int position, float offset) {

    int actuallyPosition = getActuallyPosition(position);

    final Bitmap child = mAdapter.getImage(actuallyPosition);
    final Bitmap reflection = obtainReflection(actuallyPosition, child);

    int[] wAndh = mImageRecorder.get(actuallyPosition);
    if (wAndh == null) {
        wAndh = new int[] { child.getWidth(), child.getHeight() };
        mImageRecorder.put(actuallyPosition, wAndh);
    } else {/*from w w  w .j av a 2 s .co m*/
        wAndh[0] = child.getWidth();
        wAndh[1] = child.getHeight();
    }

    if (child != null && !child.isRecycled() && canvas != null) {
        makeChildTransfromer(child, position, offset);
        canvas.drawBitmap(child, mChildTransfromer, mDrawChildPaint);
        if (reflection != null) {

            canvas.drawBitmap(reflection, mReflectionTransfromer, mDrawChildPaint);
        }
    }
}

From source file:com.atobo.safecoo.view.coverflow.CoverFlowView.java

protected final void drawChild(Canvas canvas, int position, float offset) {

    int actuallyPosition = getActuallyPosition(position);

    final Bitmap child = mAdapter.getImage(actuallyPosition);
    final Bitmap reflection = obtainReflection(actuallyPosition, child);

    int[] wAndh = mImageRecorder.get(actuallyPosition);
    if (wAndh == null) {
        wAndh = new int[] { child.getWidth(), child.getHeight() };
        mImageRecorder.put(actuallyPosition, wAndh);
    } else {//w  w w .  j a  v  a2  s  .c  o  m
        wAndh[0] = child.getWidth();
        wAndh[1] = child.getHeight();
    }

    if (child != null && !child.isRecycled() && canvas != null) {
        makeChildTransfromer(child, position, offset);
        canvas.drawBitmap(child, mChildTransfromer, mDrawChildPaint);
        if (reflection != null) {

            // canvas.drawBitmap(reflection, mReflectionTransfromer,
            //        mDrawChildPaint);
        }
    }
}

From source file:cn.edu.zafu.easemob.imagecoverflow.CoverFlowView.java

protected final void drawChild(Canvas canvas, int mid, int position, float offset) {

    int actuallyPosition = getActuallyPosition(position);

    final Bitmap child = mAdapter.getImage(actuallyPosition);
    final Bitmap reflection = obtainReflection(child);

    int[] wAndh = mImageRecorder.get(actuallyPosition);
    if (wAndh == null) {
        wAndh = new int[] { child.getWidth(), child.getHeight() };
        mImageRecorder.put(actuallyPosition, wAndh);
    } else {/*  w  w  w. j ava  2s  . c  o m*/
        wAndh[0] = child.getWidth();
        wAndh[1] = child.getHeight();
    }

    if (child != null && !child.isRecycled() && canvas != null) {
        makeChildTransformer(child, mid, position, offset);
        canvas.drawBitmap(child, mChildTransformer, mDrawChildPaint);
        if (reflection != null) {

            canvas.drawBitmap(reflection, mReflectionTransformer, mDrawChildPaint);
        }
    }
}

From source file:com.dolphinwang.imagecoverflow.CoverFlowView.java

protected final void drawChild(Canvas canvas, int position, float offset) {

    int actuallyPosition = getActuallyPosition(position);

    final Bitmap child = mAdapter.getImage(actuallyPosition);
    final Bitmap reflection = obtainReflection(actuallyPosition, child);

    int[] wAndh = mImageRecorder.get(actuallyPosition);
    if (wAndh == null) {
        wAndh = new int[] { child.getWidth(), child.getHeight() };
        mImageRecorder.put(actuallyPosition, wAndh);
    } else {//ww w .j a v a 2s. co m
        wAndh[0] = child.getWidth();
        wAndh[1] = child.getHeight();
    }
    if (child != null && !child.isRecycled() && canvas != null) {
        makeChildTransfromer(child, position, offset);
        canvas.drawBitmap(child, mChildTransfromer, mDrawChildPaint);
        if (reflection != null) {
            canvas.drawBitmap(reflection, mReflectionTransfromer, mDrawChildPaint);
        }
    }
}

From source file:com.chibatching.imgindicatortab.ImgIndicatorTab.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mViewPager == null) {
        return;/* w w w.j  a v a  2 s  .co m*/
    }

    int tabCount = mViewPager.getAdapter().getCount();
    if (tabCount == 0) {
        return;
    }

    if (mCurrentPage >= tabCount) {
        setCurrentItem(tabCount - 1);
    }

    float tabWidth = (float) (getWidth() - getPaddingLeft() - getPaddingRight()) / tabCount;
    float centerY = getPaddingTop() + (float) (getHeight() - getPaddingTop() - getPaddingBottom()) / 2;

    for (int i = 0; i < tabCount; i++) {
        float tabCenterX = (tabWidth * i) + getPaddingLeft() + tabWidth / 2;
        CharSequence text = mViewPager.getAdapter().getPageTitle(i);

        Paint textPaint;
        if (mTextCurrentPage == i) {
            textPaint = mSelectedTextPaint;
        } else {
            textPaint = mDeselectedTextPaint;
        }

        Paint.FontMetrics metrics = textPaint.getFontMetrics();
        float textWidth = textPaint.measureText(text, 0, text.length());
        float textX = tabCenterX - textWidth / 2;
        float textY = centerY - (metrics.ascent + metrics.descent) / 2;

        canvas.drawText(text, 0, text.length(), textX, textY, textPaint);
    }

    if (mIndicator == null) {
        return;
    }

    Bitmap indicatorBitmap = ((BitmapDrawable) mIndicator).getBitmap();
    int bitmapWidth = indicatorBitmap.getWidth();
    int bitmapHeight = indicatorBitmap.getHeight();

    float scale = 1f;
    if (mFitIndicator || bitmapWidth > tabWidth) {
        scale = tabWidth / bitmapWidth;
    }
    if (bitmapHeight * scale > getHeight()) {
        scale = getHeight() / bitmapHeight;
    }

    float tabCenterX = tabWidth * (mCurrentPage + mPositionOffset) + getPaddingLeft() + tabWidth / 2;
    float bitmapX = tabCenterX - (bitmapWidth * scale) / 2;
    float bitmapY = getHeight() - bitmapHeight * scale;

    // Set matrix for bitmap
    mMatrix.reset();
    mMatrix.postScale(scale, scale);
    mMatrix.postTranslate(bitmapX, bitmapY);

    canvas.drawBitmap(indicatorBitmap, mMatrix, mIndicatorPaint);
}

From source file:com.android.gallery3d.filtershow.imageshow.ImageShow.java

public void drawCompareImage(Canvas canvas, Bitmap image) {
    MasterImage master = MasterImage.getImage();
    boolean showsOriginal = master.showsOriginal();
    if (!showsOriginal && !mTouchShowOriginal)
        return;//from   w  w  w  .j  a va  2s. c  o  m
    canvas.save();
    if (image != null) {
        if (mShowOriginalDirection == 0) {
            if (Math.abs(mTouch.y - mTouchDown.y) > Math.abs(mTouch.x - mTouchDown.x)) {
                mShowOriginalDirection = UNVEIL_VERTICAL;
            } else {
                mShowOriginalDirection = UNVEIL_HORIZONTAL;
            }
        }

        int px = 0;
        int py = 0;
        if (mShowOriginalDirection == UNVEIL_VERTICAL) {
            px = mImageBounds.width();
            py = mTouch.y - mImageBounds.top;
        } else {
            px = mTouch.x - mImageBounds.left;
            py = mImageBounds.height();
            if (showsOriginal) {
                px = mImageBounds.width();
            }
        }

        Rect d = new Rect(mImageBounds.left, mImageBounds.top, mImageBounds.left + px, mImageBounds.top + py);
        if (mShowOriginalDirection == UNVEIL_HORIZONTAL) {
            if (mTouchDown.x - mTouch.x > 0) {
                d.set(mImageBounds.left + px, mImageBounds.top, mImageBounds.right, mImageBounds.top + py);
            }
        } else {
            if (mTouchDown.y - mTouch.y > 0) {
                d.set(mImageBounds.left, mImageBounds.top + py, mImageBounds.left + px, mImageBounds.bottom);
            }
        }
        canvas.clipRect(d);
        Matrix m = master.computeImageToScreen(image, 0, false);
        canvas.drawBitmap(image, m, mPaint);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);

        if (mShowOriginalDirection == UNVEIL_VERTICAL) {
            canvas.drawLine(mImageBounds.left, mTouch.y, mImageBounds.right, mTouch.y, paint);
        } else {
            canvas.drawLine(mTouch.x, mImageBounds.top, mTouch.x, mImageBounds.bottom, paint);
        }

        Rect bounds = new Rect();
        paint.setAntiAlias(true);
        paint.setTextSize(mOriginalTextSize);
        paint.getTextBounds(mOriginalText, 0, mOriginalText.length(), bounds);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        canvas.drawText(mOriginalText, mImageBounds.left + mOriginalTextMargin,
                mImageBounds.top + bounds.height() + mOriginalTextMargin, paint);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(1);
        paint.setColor(Color.WHITE);
        canvas.drawText(mOriginalText, mImageBounds.left + mOriginalTextMargin,
                mImageBounds.top + bounds.height() + mOriginalTextMargin, paint);
    }
    canvas.restore();
}

From source file:com.android.gallery3d.filtershow.imageshow.ImageShow.java

public void drawImageAndAnimate(Canvas canvas, Bitmap image) {
    if (image == null) {
        return;/*from w  w  w  . j av a 2 s .com*/
    }
    MasterImage master = MasterImage.getImage();
    Matrix m = master.computeImageToScreen(image, 0, false);
    if (m == null) {
        return;
    }

    canvas.save();

    RectF d = new RectF(0, 0, image.getWidth(), image.getHeight());
    m.mapRect(d);
    d.roundOut(mImageBounds);

    boolean showAnimatedImage = master.onGoingNewLookAnimation();
    if (!showAnimatedImage && mDidStartAnimation) {
        // animation ended, but do we have the correct image to show?
        if (master.getPreset().equals(master.getCurrentPreset())) {
            // we do, let's stop showing the animated image
            mDidStartAnimation = false;
            MasterImage.getImage().resetAnimBitmap();
        } else {
            showAnimatedImage = true;
        }
    } else if (showAnimatedImage) {
        mDidStartAnimation = true;
    }

    if (showAnimatedImage) {
        canvas.save();

        // Animation uses the image before the change
        Bitmap previousImage = master.getPreviousImage();
        Matrix mp = master.computeImageToScreen(previousImage, 0, false);
        RectF dp = new RectF(0, 0, previousImage.getWidth(), previousImage.getHeight());
        mp.mapRect(dp);
        Rect previousBounds = new Rect();
        dp.roundOut(previousBounds);
        float centerX = dp.centerX();
        float centerY = dp.centerY();
        boolean needsToDrawImage = true;

        if (master.getCurrentLookAnimation() == MasterImage.CIRCLE_ANIMATION) {
            float maskScale = MasterImage.getImage().getMaskScale();
            if (maskScale >= 0.0f) {
                float maskW = sMask.getWidth() / 2.0f;
                float maskH = sMask.getHeight() / 2.0f;
                Point point = mActivity.hintTouchPoint(this);
                float maxMaskScale = 2 * Math.max(getWidth(), getHeight()) / Math.min(maskW, maskH);
                maskScale = maskScale * maxMaskScale;
                float x = point.x - maskW * maskScale;
                float y = point.y - maskH * maskScale;

                // Prepare the shader
                mShaderMatrix.reset();
                mShaderMatrix.setScale(1.0f / maskScale, 1.0f / maskScale);
                mShaderMatrix.preTranslate(-x + mImageBounds.left, -y + mImageBounds.top);
                float scaleImageX = mImageBounds.width() / (float) image.getWidth();
                float scaleImageY = mImageBounds.height() / (float) image.getHeight();
                mShaderMatrix.preScale(scaleImageX, scaleImageY);
                mMaskPaint.reset();
                Shader maskShader = createShader(image);
                maskShader.setLocalMatrix(mShaderMatrix);
                mMaskPaint.setShader(maskShader);

                drawShadow(canvas, mImageBounds); // as needed
                canvas.drawBitmap(previousImage, m, mPaint);
                canvas.clipRect(mImageBounds);
                canvas.translate(x, y);
                canvas.scale(maskScale, maskScale);
                canvas.drawBitmap(sMask, 0, 0, mMaskPaint);
                needsToDrawImage = false;
            }
        } else if (master.getCurrentLookAnimation() == MasterImage.ROTATE_ANIMATION) {
            Rect d1 = computeImageBounds(master.getPreviousImage().getHeight(),
                    master.getPreviousImage().getWidth());
            Rect d2 = computeImageBounds(master.getPreviousImage().getWidth(),
                    master.getPreviousImage().getHeight());
            float finalScale = d1.width() / (float) d2.height();
            finalScale = (1.0f * (1.0f - master.getAnimFraction())) + (finalScale * master.getAnimFraction());
            canvas.rotate(master.getAnimRotationValue(), centerX, centerY);
            canvas.scale(finalScale, finalScale, centerX, centerY);
        } else if (master.getCurrentLookAnimation() == MasterImage.MIRROR_ANIMATION) {
            if (master.getCurrentFilterRepresentation() instanceof FilterMirrorRepresentation) {
                FilterMirrorRepresentation rep = (FilterMirrorRepresentation) master
                        .getCurrentFilterRepresentation();

                ImagePreset preset = master.getPreset();
                ArrayList<FilterRepresentation> geometry = (ArrayList<FilterRepresentation>) preset
                        .getGeometryFilters();
                GeometryMathUtils.GeometryHolder holder = null;
                holder = GeometryMathUtils.unpackGeometry(geometry);

                if (holder.rotation.value() == 90 || holder.rotation.value() == 270) {
                    if (rep.isHorizontal() && !rep.isVertical()) {
                        canvas.scale(1, master.getAnimRotationValue(), centerX, centerY);
                    } else if (rep.isVertical() && !rep.isHorizontal()) {
                        canvas.scale(1, master.getAnimRotationValue(), centerX, centerY);
                    } else if (rep.isHorizontal() && rep.isVertical()) {
                        canvas.scale(master.getAnimRotationValue(), 1, centerX, centerY);
                    } else {
                        canvas.scale(master.getAnimRotationValue(), 1, centerX, centerY);
                    }
                } else {
                    if (rep.isHorizontal() && !rep.isVertical()) {
                        canvas.scale(master.getAnimRotationValue(), 1, centerX, centerY);
                    } else if (rep.isVertical() && !rep.isHorizontal()) {
                        canvas.scale(master.getAnimRotationValue(), 1, centerX, centerY);
                    } else if (rep.isHorizontal() && rep.isVertical()) {
                        canvas.scale(1, master.getAnimRotationValue(), centerX, centerY);
                    } else {
                        canvas.scale(1, master.getAnimRotationValue(), centerX, centerY);
                    }
                }
            }
        }

        if (needsToDrawImage) {
            drawShadow(canvas, previousBounds); // as needed
            canvas.drawBitmap(previousImage, mp, mPaint);
        }

        canvas.restore();
    } else {
        drawShadow(canvas, mImageBounds); // as needed
        canvas.drawBitmap(image, m, mPaint);
    }

    canvas.restore();
}

From source file:com.android.ex.chips.RecipientEditTextView.java

private Bitmap createUnselectedChip(final RecipientEntry contact, final TextPaint paint,
        final boolean leaveBlankIconSpacer) {
    // Ellipsize the text so that it takes AT MOST the entire width of the
    // autocomplete text entry area. Make sure to leave space for padding
    // on the sides.
    final int height = (int) mChipHeight;
    int iconWidth = height;
    final float[] widths = new float[1];
    paint.getTextWidths(" ", widths);
    final float availableWidth = calculateAvailableWidth();
    final String chipDisplayText = createChipDisplayText(contact);
    final CharSequence ellipsizedText = ellipsizeText(chipDisplayText, paint,
            availableWidth - iconWidth - widths[0]);
    // Make sure there is a minimum chip width so the user can ALWAYS
    // tap a chip without difficulty.
    final int width = Math.max(iconWidth * 2,
            (int) Math.floor(paint.measureText(ellipsizedText, 0, ellipsizedText.length())) + mChipPadding * 2
                    + iconWidth);// w w w.  j a va2  s .c  om
    // Create the background of the chip.
    final Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(tmpBitmap);
    final Drawable background = getChipBackground(contact);
    if (background != null) {
        background.setBounds(0, 0, width, height);
        background.draw(canvas);
        // Don't draw photos for recipients that have been typed in OR generated on the fly.
        final long contactId = contact.getContactId();
        final boolean drawPhotos = isPhoneQuery() ? contactId != RecipientEntry.INVALID_CONTACT
                : contactId != RecipientEntry.INVALID_CONTACT && contactId != RecipientEntry.GENERATED_CONTACT
                        && !TextUtils.isEmpty(contact.getDisplayName());
        if (drawPhotos) {
            byte[] photoBytes = contact.getPhotoBytes();
            // There may not be a photo yet if anything but the first contact address
            // was selected.
            if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
                // TODO: cache this in the recipient entry?
                getAdapter().fetchPhoto(contact, contact.getPhotoThumbnailUri());
                photoBytes = contact.getPhotoBytes();
            }
            Bitmap photo;
            if (photoBytes != null)
                photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
            else // TODO: can the scaled down default photo be cached?
                photo = mDefaultContactPhoto;
            // Draw the photo on the left side.
            if (photo != null) {
                final RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
                final Rect backgroundPadding = new Rect();
                mChipBackground.getPadding(backgroundPadding);
                final RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
                        0 + backgroundPadding.top, width - backgroundPadding.right,
                        height - backgroundPadding.bottom);
                final Matrix matrix = new Matrix();
                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
                canvas.drawBitmap(photo, matrix, paint);
            }
        } else if (!leaveBlankIconSpacer || isPhoneQuery())
            iconWidth = 0;
        paint.setColor(ContextCompat.getColor(getContext(), android.R.color.black));
        // Vertically center the text in the chip.
        canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
                getTextYOffset((String) ellipsizedText, paint, height), paint);
    } else
        Log.w(TAG, "Unable to draw a background for the chips as it was never set");
    return tmpBitmap;
}