Example usage for android.graphics Canvas restore

List of usage examples for android.graphics Canvas restore

Introduction

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

Prototype

public void restore() 

Source Link

Document

This call balances a previous call to save(), and is used to remove all modifications to the matrix/clip state since the last save call.

Usage

From source file:com.acceleratedio.pac_n_zoom.DrawSVG.java

public ArrayList<ImageView> DrawSVG(Context context, ImageView orgnlImageView, RelativeLayout rel_anm_lo) {

    paint.setColor(Color.WHITE);/*from w w w  .  j av a  2  s  .co  m*/
    paint.setStyle(Paint.Style.FILL);
    LoadSVG.SVGData data = AnimActivity.svg_data;
    ArrayList<ImageView> imgViews = new ArrayList<ImageView>();
    imgViews.add(orgnlImageView);

    if (data.symbl != null) {

        ArrayList<String> sprt_ordr = data.svg.ordr;
        int sym_mbr = 0;
        Bitmap bitmap;
        Canvas canvas;

        // - Loop through the sprites 
        int sprt_nmbr = sprt_ordr.size();
        data.svg.initScl = new float[sprt_nmbr];
        float[] initScl = data.svg.initScl;

        for (int sprt_mbr = 1; sprt_mbr < sprt_nmbr; sprt_mbr += 1) {

            String sprt_id = sprt_ordr.get(sprt_mbr); // e.g., id="g2_0"

            if (Integer.parseInt(sprt_id.substring(sprt_id.indexOf('_') + 1)) > 0) {
                // The symbol is already drawn; replicate the view   
                String init_sprt = sprt_id.substring(0, sprt_id.indexOf('_') + 1) + '0';
                String svg_ordr = data.svg.svg_ordr;
                String cnt_str = svg_ordr.substring(0, svg_ordr.indexOf(init_sprt));
                ImageView init_vw = imgViews.get(StringUtils.countMatches(cnt_str, ","));
                Bitmap initBmp = ((BitmapDrawable) init_vw.getDrawable()).getBitmap();

                bitmap = Bitmap.createBitmap(initBmp.getWidth(), initBmp.getHeight(), initBmp.getConfig());

                canvas = new Canvas(bitmap);
                canvas.save(Canvas.MATRIX_SAVE_FLAG);
                xfrmInit crt_sprt = getInitSpriteAttrib(sprt_id);
                canvas.scale(crt_sprt.scl, crt_sprt.scl);
                initScl[sprt_mbr] = crt_sprt.scl;
                canvas.translate(0, 0);
            } else {
                // The symbol needs to be drawn; a new view   is used
                bitmap = getCreatBmp(rel_anm_lo);
                canvas = new Canvas(bitmap);
                canvas.save(Canvas.MATRIX_SAVE_FLAG);

                // - Set the init values
                xfrmInit crt_sprt = getInitSpriteAttrib(sprt_id);
                canvas.scale(crt_sprt.scl, crt_sprt.scl);
                initScl[sprt_mbr] = crt_sprt.scl;
                canvas.translate(0, 0);

                // - Draw the bitmap
                LoadSVG.symbol crt_sym = data.symbl.get(sym_mbr);
                ArrayList<LoadSVG.path> pths = crt_sym.pths;
                int pth_nmbr = pths.size();

                // Loop through the paths
                for (int pth_mbr = 0; pth_mbr < pth_nmbr; pth_mbr += 1) {

                    LoadSVG.path crt_pth = pths.get(pth_mbr);
                    final Path path = new Path();
                    final Paint paint = new Paint();
                    /* Debug
                    if (pth_mbr + 1 == pth_nmbr) {
                            
                       String log_str = "Paths: pth_mbr = " +
                          String.valueOf(pth_mbr) + "; color = " + crt_pth.clr;
                            
                       Log.d("DrawSVG", log_str);
                    }
                    */
                    paint.setColor(Color.parseColor(crt_pth.clr));
                    paint.setAntiAlias(true);
                    paint.setStyle(Paint.Style.FILL_AND_STROKE);
                    ld_pth_pnts(crt_pth.pth, path);
                    path.close();
                    path.setFillType(Path.FillType.EVEN_ODD);
                    canvas.drawPath(path, paint);
                }

                canvas.restore();
                sym_mbr += 1;
            }

            ImageView iv = new ImageView(context);
            iv.setImageBitmap(bitmap);

            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

            iv.draw(canvas);
            iv.setLayoutParams(rlp);
            iv.setBackgroundColor(Color.TRANSPARENT);
            imgViews.add(iv);
        } // sprites
    } // if symbol

    return imgViews;
}

From source file:org.telegram.ui.Components.ChatAttachAlert.java

public ChatAttachAlert(Context context, final ChatActivity parentFragment) {
    super(context, false);
    baseFragment = parentFragment;/*from  w  w  w .j av  a2s.  co m*/
    setDelegate(this);
    setUseRevealAnimation(true);
    checkCamera(false);
    if (deviceHasGoodCamera) {
        CameraController.getInstance().initCamera();
    }
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.albumsDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInlineHints);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.cameraInitied);
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow);

    containerView = listView = new RecyclerListView(context) {

        private int lastWidth;
        private int lastHeight;

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (cameraAnimationInProgress) {
                return true;
            } else if (cameraOpened) {
                return processTouchEvent(ev);
            } else if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0
                    && ev.getY() < scrollOffsetY) {
                dismiss();
                return true;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (cameraAnimationInProgress) {
                return true;
            } else if (cameraOpened) {
                return processTouchEvent(event);
            }
            return !isDismissed() && super.onTouchEvent(event);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21) {
                height -= AndroidUtilities.statusBarHeight;
            }
            int contentSize = backgroundPaddingTop + AndroidUtilities.dp(294)
                    + (SearchQuery.inlineBots.isEmpty() ? 0
                            : ((int) Math.ceil(SearchQuery.inlineBots.size() / 4.0f) * AndroidUtilities.dp(100)
                                    + AndroidUtilities.dp(12)));
            int padding = contentSize == AndroidUtilities.dp(294) ? 0
                    : Math.max(0, (height - AndroidUtilities.dp(294)));
            if (padding != 0 && contentSize < height) {
                padding -= (height - contentSize);
            }
            if (padding == 0) {
                padding = backgroundPaddingTop;
            }
            if (getPaddingTop() != padding) {
                ignoreLayout = true;
                setPadding(backgroundPaddingLeft, padding, backgroundPaddingLeft, 0);
                ignoreLayout = false;
            }
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(Math.min(contentSize, height), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int width = right - left;
            int height = bottom - top;

            int newPosition = -1;
            int newTop = 0;

            int count = listView.getChildCount();
            int lastVisibleItemPosition = -1;
            int lastVisibleItemPositionTop = 0;
            if (count > 0) {
                View child = listView.getChildAt(listView.getChildCount() - 1);
                Holder holder = (Holder) listView.findContainingViewHolder(child);
                if (holder != null) {
                    lastVisibleItemPosition = holder.getAdapterPosition();
                    lastVisibleItemPositionTop = child.getTop();
                }
            }

            if (lastVisibleItemPosition >= 0 && height - lastHeight != 0) {
                newPosition = lastVisibleItemPosition;
                newTop = lastVisibleItemPositionTop + height - lastHeight - getPaddingTop();
            }

            super.onLayout(changed, left, top, right, bottom);

            if (newPosition != -1) {
                ignoreLayout = true;
                layoutManager.scrollToPositionWithOffset(newPosition, newTop);
                super.onLayout(false, left, top, right, bottom);
                ignoreLayout = false;
            }

            lastHeight = height;
            lastWidth = width;

            updateLayout();
            checkCameraViewPosition();
        }

        @Override
        public void onDraw(Canvas canvas) {
            if (useRevealAnimation && Build.VERSION.SDK_INT <= 19) {
                canvas.save();
                canvas.clipRect(backgroundPaddingLeft, scrollOffsetY,
                        getMeasuredWidth() - backgroundPaddingLeft, getMeasuredHeight());
                if (revealAnimationInProgress) {
                    canvas.drawCircle(revealX, revealY, revealRadius, ciclePaint);
                } else {
                    canvas.drawRect(backgroundPaddingLeft, scrollOffsetY,
                            getMeasuredWidth() - backgroundPaddingLeft, getMeasuredHeight(), ciclePaint);
                }
                canvas.restore();
            } else {
                shadowDrawable.setBounds(0, scrollOffsetY - backgroundPaddingTop, getMeasuredWidth(),
                        getMeasuredHeight());
                shadowDrawable.draw(canvas);
            }
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            checkCameraViewPosition();
        }
    };

    listView.setWillNotDraw(false);
    listView.setClipToPadding(false);
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(getContext()));
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setAdapter(adapter = new ListAdapter(context));
    listView.setVerticalScrollBarEnabled(false);
    listView.setEnabled(true);
    listView.setGlowColor(0xfff5f6f7);
    listView.addItemDecoration(new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.top = 0;
            outRect.bottom = 0;
        }
    });

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (listView.getChildCount() <= 0) {
                return;
            }
            if (hintShowed) {
                if (layoutManager.findLastVisibleItemPosition() > 1) {
                    hideHint();
                    hintShowed = false;
                    ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit()
                            .putBoolean("bothint", true).commit();
                }
            }
            updateLayout();
            checkCameraViewPosition();
        }
    });
    containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);

    attachView = new FrameLayout(context) {
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(294), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int width = right - left;
            int height = bottom - top;
            int t = AndroidUtilities.dp(8);
            attachPhotoRecyclerView.layout(0, t, width, t + attachPhotoRecyclerView.getMeasuredHeight());
            progressView.layout(0, t, width, t + progressView.getMeasuredHeight());
            lineView.layout(0, AndroidUtilities.dp(96), width,
                    AndroidUtilities.dp(96) + lineView.getMeasuredHeight());
            hintTextView.layout(width - hintTextView.getMeasuredWidth() - AndroidUtilities.dp(5),
                    height - hintTextView.getMeasuredHeight() - AndroidUtilities.dp(5),
                    width - AndroidUtilities.dp(5), height - AndroidUtilities.dp(5));

            int diff = (width - AndroidUtilities.dp(85 * 4 + 20)) / 3;
            for (int a = 0; a < 8; a++) {
                int y = AndroidUtilities.dp(105 + 95 * (a / 4));
                int x = AndroidUtilities.dp(10) + (a % 4) * (AndroidUtilities.dp(85) + diff);
                views[a].layout(x, y, x + views[a].getMeasuredWidth(), y + views[a].getMeasuredHeight());
            }
        }
    };

    views[8] = attachPhotoRecyclerView = new RecyclerListView(context);
    attachPhotoRecyclerView.setVerticalScrollBarEnabled(true);
    attachPhotoRecyclerView.setAdapter(photoAttachAdapter = new PhotoAttachAdapter(context));
    attachPhotoRecyclerView.setClipToPadding(false);
    attachPhotoRecyclerView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0);
    attachPhotoRecyclerView.setItemAnimator(null);
    attachPhotoRecyclerView.setLayoutAnimation(null);
    attachPhotoRecyclerView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    attachView.addView(attachPhotoRecyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 80));
    attachPhotoLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    attachPhotoLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    attachPhotoRecyclerView.setLayoutManager(attachPhotoLayoutManager);
    attachPhotoRecyclerView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void onItemClick(View view, int position) {
            if (baseFragment == null || baseFragment.getParentActivity() == null) {
                return;
            }
            if (!deviceHasGoodCamera || position != 0) {
                if (deviceHasGoodCamera) {
                    position--;
                }
                if (MediaController.allPhotosAlbumEntry == null) {
                    return;
                }
                ArrayList<Object> arrayList = (ArrayList) MediaController.allPhotosAlbumEntry.photos;
                if (position < 0 || position >= arrayList.size()) {
                    return;
                }
                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                PhotoViewer.getInstance().openPhotoForSelect(arrayList, position, 0, ChatAttachAlert.this,
                        baseFragment);
                AndroidUtilities.hideKeyboard(baseFragment.getFragmentView().findFocus());
            } else {
                openCamera();
            }
        }
    });
    attachPhotoRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkCameraViewPosition();
        }
    });

    views[9] = progressView = new EmptyTextProgressView(context);
    if (Build.VERSION.SDK_INT >= 23 && getContext().checkSelfPermission(
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        progressView.setText(LocaleController.getString("PermissionStorage", R.string.PermissionStorage));
        progressView.setTextSize(16);
    } else {
        progressView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos));
        progressView.setTextSize(20);
    }
    attachView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 80));
    attachPhotoRecyclerView.setEmptyView(progressView);

    views[10] = lineView = new View(getContext()) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }
    };
    lineView.setBackgroundColor(ContextCompat.getColor(context, R.color.divider));
    attachView.addView(lineView,
            new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, Gravity.TOP | Gravity.LEFT));
    CharSequence[] items = new CharSequence[] { LocaleController.getString("ChatCamera", R.string.ChatCamera),
            LocaleController.getString("ChatGallery", R.string.ChatGallery),
            LocaleController.getString("ChatVideo", R.string.ChatVideo),
            LocaleController.getString("AttachMusic", R.string.AttachMusic),
            LocaleController.getString("ChatDocument", R.string.ChatDocument),
            LocaleController.getString("AttachContact", R.string.AttachContact),
            LocaleController.getString("ChatLocation", R.string.ChatLocation), "" };
    for (int a = 0; a < 8; a++) {
        AttachButton attachButton = new AttachButton(context);
        attachButton.setTextAndIcon(items[a], Theme.attachButtonDrawables[a]);
        attachView.addView(attachButton, LayoutHelper.createFrame(85, 90, Gravity.LEFT | Gravity.TOP));
        attachButton.setTag(a);
        views[a] = attachButton;
        if (a == 7) {
            sendPhotosButton = attachButton;
            sendPhotosButton.imageView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        }
        attachButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delegate.didPressedButton((Integer) v.getTag());
            }
        });
    }

    hintTextView = new TextView(context);
    hintTextView.setBackgroundResource(R.drawable.tooltip);
    hintTextView.setTextColor(Theme.CHAT_GIF_HINT_TEXT_COLOR);
    hintTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    hintTextView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
    hintTextView.setText(LocaleController.getString("AttachBotsHelp", R.string.AttachBotsHelp));
    hintTextView.setGravity(Gravity.CENTER_VERTICAL);
    hintTextView.setVisibility(View.INVISIBLE);
    hintTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.scroll_tip, 0, 0, 0);
    hintTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    attachView.addView(hintTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 32,
            Gravity.RIGHT | Gravity.BOTTOM, 5, 0, 5, 5));

    for (int a = 0; a < 8; a++) {
        viewsCache.add(photoAttachAdapter.createHolder());
    }

    if (loading) {
        progressView.showProgress();
    } else {
        progressView.showTextView();
    }

    if (Build.VERSION.SDK_INT >= 16) {
        recordTime = new TextView(context);
        recordTime.setBackgroundResource(R.drawable.system);
        recordTime.getBackground()
                .setColorFilter(new PorterDuffColorFilter(0x66000000, PorterDuff.Mode.MULTIPLY));
        recordTime.setText("00:00");
        recordTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        recordTime.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        recordTime.setAlpha(0.0f);
        recordTime.setTextColor(0xffffffff);
        recordTime.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(10),
                AndroidUtilities.dp(5));
        container.addView(recordTime, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0));

        cameraPanel = new FrameLayout(context) {
            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                int cx = getMeasuredWidth() / 2;
                int cy = getMeasuredHeight() / 2;
                int cx2;
                int cy2;
                shutterButton.layout(cx - shutterButton.getMeasuredWidth() / 2,
                        cy - shutterButton.getMeasuredHeight() / 2, cx + shutterButton.getMeasuredWidth() / 2,
                        cy + shutterButton.getMeasuredHeight() / 2);
                if (getMeasuredWidth() == AndroidUtilities.dp(100)) {
                    cx = cx2 = getMeasuredWidth() / 2;
                    cy2 = cy + cy / 2 + AndroidUtilities.dp(17);
                    cy = cy / 2 - AndroidUtilities.dp(17);
                } else {
                    cx2 = cx + cx / 2 + AndroidUtilities.dp(17);
                    cx = cx / 2 - AndroidUtilities.dp(17);
                    cy = cy2 = getMeasuredHeight() / 2;
                }
                switchCameraButton.layout(cx2 - switchCameraButton.getMeasuredWidth() / 2,
                        cy2 - switchCameraButton.getMeasuredHeight() / 2,
                        cx2 + switchCameraButton.getMeasuredWidth() / 2,
                        cy2 + switchCameraButton.getMeasuredHeight() / 2);
                for (int a = 0; a < 2; a++) {
                    flashModeButton[a].layout(cx - flashModeButton[a].getMeasuredWidth() / 2,
                            cy - flashModeButton[a].getMeasuredHeight() / 2,
                            cx + flashModeButton[a].getMeasuredWidth() / 2,
                            cy + flashModeButton[a].getMeasuredHeight() / 2);
                }
            }
        };
        cameraPanel.setVisibility(View.GONE);
        cameraPanel.setAlpha(0.0f);
        container.addView(cameraPanel,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.BOTTOM));

        shutterButton = new ShutterButton(context);
        cameraPanel.addView(shutterButton, LayoutHelper.createFrame(84, 84, Gravity.CENTER));
        shutterButton.setDelegate(new ShutterButton.ShutterButtonDelegate() {
            @Override
            public void shutterLongPressed() {
                if (takingPhoto || baseFragment == null || baseFragment.getParentActivity() == null) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    if (baseFragment.getParentActivity().checkSelfPermission(
                            Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                        baseFragment.getParentActivity()
                                .requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, 21);
                        return;
                    }
                }
                for (int a = 0; a < 2; a++) {
                    flashModeButton[a].setAlpha(0.0f);
                }
                switchCameraButton.setAlpha(0.0f);
                cameraFile = AndroidUtilities.generateVideoPath();
                recordTime.setAlpha(1.0f);
                recordTime.setText("00:00");
                videoRecordTime = 0;
                videoRecordRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (videoRecordRunnable == null) {
                            return;
                        }
                        videoRecordTime++;
                        recordTime.setText(
                                String.format("%02d:%02d", videoRecordTime / 60, videoRecordTime % 60));
                        AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
                    }
                };
                AndroidUtilities.lockOrientation(parentFragment.getParentActivity());
                CameraController.getInstance().recordVideo(cameraView.getCameraSession(), cameraFile,
                        new CameraController.VideoTakeCallback() {
                            @Override
                            public void onFinishVideoRecording(final Bitmap thumb) {
                                if (cameraFile == null || baseFragment == null) {
                                    return;
                                }
                                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                                cameraPhoto = new ArrayList<>();
                                cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0,
                                        cameraFile.getAbsolutePath(), 0, true));
                                PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2,
                                        new PhotoViewer.EmptyPhotoViewerProvider() {
                                            @Override
                                            public Bitmap getThumbForPhoto(MessageObject messageObject,
                                                    TLRPC.FileLocation fileLocation, int index) {
                                                return thumb;
                                            }

                                            @TargetApi(16)
                                            @Override
                                            public boolean cancelButtonPressed() {
                                                if (cameraOpened && cameraView != null && cameraFile != null) {
                                                    cameraFile.delete();
                                                    AndroidUtilities.runOnUIThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (cameraView != null && !isDismissed()
                                                                    && Build.VERSION.SDK_INT >= 21) {
                                                                cameraView.setSystemUiVisibility(
                                                                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                                                                | View.SYSTEM_UI_FLAG_FULLSCREEN);
                                                            }
                                                        }
                                                    }, 1000);
                                                    CameraController.getInstance()
                                                            .startPreview(cameraView.getCameraSession());
                                                    cameraFile = null;
                                                }
                                                return true;
                                            }

                                            @Override
                                            public void sendButtonPressed(int index) {
                                                if (cameraFile == null) {
                                                    return;
                                                }
                                                AndroidUtilities
                                                        .addMediaToGallery(cameraFile.getAbsolutePath());
                                                baseFragment.sendMedia(
                                                        (MediaController.PhotoEntry) cameraPhoto.get(0),
                                                        PhotoViewer.getInstance().isMuteVideo());
                                                closeCamera(false);
                                                dismiss();
                                                cameraFile = null;
                                            }
                                        }, baseFragment);
                            }
                        });
                AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
                shutterButton.setState(ShutterButton.State.RECORDING, true);
            }

            @Override
            public void shutterCancel() {
                cameraFile.delete();
                resetRecordState();
                CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), true);
            }

            @Override
            public void shutterReleased() {
                if (takingPhoto) {
                    return;
                }
                if (shutterButton.getState() == ShutterButton.State.RECORDING) {
                    resetRecordState();
                    CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), false);
                    shutterButton.setState(ShutterButton.State.DEFAULT, true);
                    return;
                }
                cameraFile = AndroidUtilities.generatePicturePath();
                takingPhoto = CameraController.getInstance().takePicture(cameraFile,
                        cameraView.getCameraSession(), new Runnable() {
                            @Override
                            public void run() {
                                takingPhoto = false;
                                if (cameraFile == null || baseFragment == null) {
                                    return;
                                }
                                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                                cameraPhoto = new ArrayList<>();
                                int orientation = 0;
                                try {
                                    ExifInterface ei = new ExifInterface(cameraFile.getAbsolutePath());
                                    int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                            ExifInterface.ORIENTATION_NORMAL);
                                    switch (exif) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        orientation = 90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        orientation = 180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        orientation = 270;
                                        break;
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                                cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0,
                                        cameraFile.getAbsolutePath(), orientation, false));
                                PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2,
                                        new PhotoViewer.EmptyPhotoViewerProvider() {
                                            @TargetApi(16)
                                            @Override
                                            public boolean cancelButtonPressed() {
                                                if (cameraOpened && cameraView != null && cameraFile != null) {
                                                    cameraFile.delete();
                                                    AndroidUtilities.runOnUIThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (cameraView != null && !isDismissed()
                                                                    && Build.VERSION.SDK_INT >= 21) {
                                                                cameraView.setSystemUiVisibility(
                                                                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                                                                | View.SYSTEM_UI_FLAG_FULLSCREEN);
                                                            }
                                                        }
                                                    }, 1000);
                                                    CameraController.getInstance()
                                                            .startPreview(cameraView.getCameraSession());
                                                    cameraFile = null;
                                                }
                                                return true;
                                            }

                                            @Override
                                            public void sendButtonPressed(int index) {
                                                if (cameraFile == null) {
                                                    return;
                                                }
                                                AndroidUtilities
                                                        .addMediaToGallery(cameraFile.getAbsolutePath());
                                                baseFragment.sendMedia(
                                                        (MediaController.PhotoEntry) cameraPhoto.get(0), false);
                                                closeCamera(false);
                                                dismiss();
                                                cameraFile = null;
                                            }

                                            @Override
                                            public boolean scaleToFill() {
                                                return true;
                                            }
                                        }, baseFragment);
                            }
                        });
            }
        });

        switchCameraButton = new ImageView(context);
        switchCameraButton.setScaleType(ImageView.ScaleType.CENTER);
        cameraPanel.addView(switchCameraButton,
                LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.CENTER_VERTICAL));
        switchCameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (takingPhoto || cameraView == null || !cameraView.isInitied()) {
                    return;
                }
                cameraInitied = false;
                cameraView.switchCamera();
                ObjectAnimator animator = ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 0.0f)
                        .setDuration(100);
                animator.addListener(new AnimatorListenerAdapterProxy() {
                    @Override
                    public void onAnimationEnd(Animator animator) {
                        switchCameraButton.setImageResource(cameraView.isFrontface() ? R.drawable.camera_revert1
                                : R.drawable.camera_revert2);
                        ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 1.0f).setDuration(100).start();
                    }
                });
                animator.start();
            }
        });

        for (int a = 0; a < 2; a++) {
            flashModeButton[a] = new ImageView(context);
            flashModeButton[a].setScaleType(ImageView.ScaleType.CENTER);
            flashModeButton[a].setVisibility(View.INVISIBLE);
            cameraPanel.addView(flashModeButton[a],
                    LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
            flashModeButton[a].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View currentImage) {
                    if (flashAnimationInProgress || cameraView == null || !cameraView.isInitied()
                            || !cameraOpened) {
                        return;
                    }
                    String current = cameraView.getCameraSession().getCurrentFlashMode();
                    String next = cameraView.getCameraSession().getNextFlashMode();
                    if (current.equals(next)) {
                        return;
                    }
                    cameraView.getCameraSession().setCurrentFlashMode(next);
                    flashAnimationInProgress = true;
                    ImageView nextImage = flashModeButton[0] == currentImage ? flashModeButton[1]
                            : flashModeButton[0];
                    nextImage.setVisibility(View.VISIBLE);
                    setCameraFlashModeIcon(nextImage, next);
                    AnimatorSet animatorSet = new AnimatorSet();
                    animatorSet.playTogether(
                            ObjectAnimator.ofFloat(currentImage, "translationY", 0, AndroidUtilities.dp(48)),
                            ObjectAnimator.ofFloat(nextImage, "translationY", -AndroidUtilities.dp(48), 0),
                            ObjectAnimator.ofFloat(currentImage, "alpha", 1.0f, 0.0f),
                            ObjectAnimator.ofFloat(nextImage, "alpha", 0.0f, 1.0f));
                    animatorSet.setDuration(200);
                    animatorSet.addListener(new AnimatorListenerAdapterProxy() {
                        @Override
                        public void onAnimationEnd(Animator animator) {
                            flashAnimationInProgress = false;
                            currentImage.setVisibility(View.INVISIBLE);
                        }
                    });
                    animatorSet.start();
                }
            });
        }
    }
}

From source file:com.android.launcher2.PagedView.java

@Override
protected void dispatchDraw(Canvas canvas) {
    int halfScreenSize = getMeasuredWidth() / 2;
    // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
    // Otherwise it is equal to the scaled overscroll position.
    int screenCenter = mOverScrollX + halfScreenSize;

    if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
        // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
        // set it for the next frame
        mForceScreenScrolled = false;/*  w  w  w  .j a v a2s.  c o  m*/
        screenScrolled(screenCenter);
        mLastScreenCenter = screenCenter;
    }

    // Find out which screens are visible; as an optimization we only call draw on them
    final int pageCount = getChildCount();
    if (pageCount > 0) {
        getVisiblePages(mTempVisiblePagesRange);
        final int leftScreen = mTempVisiblePagesRange[0];
        final int rightScreen = mTempVisiblePagesRange[1];
        if (leftScreen != -1 && rightScreen != -1) {
            final long drawingTime = getDrawingTime();
            // Clip to the bounds
            canvas.save();
            canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
                    getScrollY() + getBottom() - getTop());

            for (int i = getChildCount() - 1; i >= 0; i--) {
                final View v = getPageAt(i);
                if (mForceDrawAllChildrenNextFrame
                        || (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
                    drawChild(canvas, v, drawingTime);
                }
            }
            mForceDrawAllChildrenNextFrame = false;
            canvas.restore();
        }
    }
}

From source file:am.widget.indicatortabstrip.IndicatorTabStrip.java

/**
 * Tag/*from   w w w  .  jav a 2s.  co  m*/
 *
 * @param canvas     
 * @param position   ???
 * @param itemWidth  ?
 * @param itemHeight ?
 */
@SuppressWarnings("unused")
protected void drawTag(Canvas canvas, int position, int itemWidth, int itemHeight) {
    if (mAdapter == null || !mAdapter.isTagEnable(position))
        return;
    String text = mAdapter.getTag(position) == null ? "" : mAdapter.getTag(position);
    mTextPaint.setTextSize(mTagTextSize);
    mTextPaint.setColor(mTagTextColor);
    mTextPaint.getTextBounds(text, 0, text.length(), mTextMeasureBounds);
    final int textWidth = mTextMeasureBounds.width();
    final int textHeight = mTextMeasureBounds.height();
    final int tagBackgroundWidth = mTagBackground == null ? 0 : mTagBackground.getIntrinsicWidth();
    final int tagBackgroundHeight = mTagBackground == null ? 0 : mTagBackground.getIntrinsicHeight();
    int tagWidth;
    int tagHeight;
    switch (mTagMinSizeMode) {
    default:
    case TAG_MIN_SIZE_MODE_HAS_TEXT:
        if ("".equals(text)) {
            tagWidth = Math.min(mTagMinWidth, tagBackgroundWidth);
            tagHeight = Math.min(mTagMinHeight, tagBackgroundHeight);
            break;
        }
    case TAG_MIN_SIZE_MODE_ALWAYS:
        tagWidth = Math.max(textWidth + mTagLocation.getPaddingLeft() + mTagLocation.getPaddingRight(),
                Math.max(mTagMinWidth, tagBackgroundWidth));
        tagHeight = Math.max(textHeight + mTagLocation.getPaddingTop() + mTagLocation.getPaddingBottom(),
                Math.max(mTagMinHeight, tagBackgroundHeight));
        break;
    }
    final int rightTabX = position == getItemCount() - 1 ? getWidth() - ViewCompat.getPaddingEnd(this)
            : ViewCompat.getPaddingStart(this) + (itemWidth + getIntervalWidth()) * position + itemWidth;
    final int rightTagX = rightTabX - mTagLocation.getMarginRight();
    final int tagY = getPaddingTop() + mTagLocation.getMarginTop();
    final int leftTagX = rightTagX - tagWidth;
    final float tagCenterX = leftTagX + tagWidth * 0.5f;
    final float tagCenterY = tagY + tagWidth * 0.5f;
    canvas.save();
    if (mTagBackground != null) {
        mTagBackground.setBounds(0, 0, tagWidth, tagHeight);
        canvas.translate(leftTagX, tagY);
        mTagBackground.draw(canvas);
        if (!"".equals(text)) {
            canvas.translate(tagWidth * 0.5f, tagHeight * 0.5f + mTagTextDesc);
            canvas.drawText(text, 0, 0, mTextPaint);
        }
    } else {
        canvas.translate(tagCenterX, tagCenterY + mTagTextDesc);
        canvas.drawText(text, 0, 0, mTextPaint);
    }
    canvas.restore();
}

From source file:org.bangbang.support.v4.widget.HListView.java

/**
     * Draws a divider for the given child in the given bounds.
     *//from  w  w  w  . ja v  a  2s  .  com
     * @param canvas The canvas to draw to.
     * @param bounds The bounds of the divider.
     * @param childIndex The index of child (of the View) above the divider.
     *            This will be -1 if there is no child above the divider to be
     *            drawn.
     */
    void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
        // This widget draws the same divider for all children
        final Drawable divider = mDivider;
        final boolean clipDivider = mClipDivider;

        if (!clipDivider) {
            divider.setBounds(bounds);
        } else {
            canvas.save();
            canvas.clipRect(bounds);
        }

        divider.draw(canvas);

        if (clipDivider) {
            canvas.restore();
        }
    }

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;/*www .  ja v  a2s.  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.appunite.list.HorizontalListView.java

void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
    final int width = drawable.getMinimumWidth();

    canvas.save();/*from  ww w  .  j  av  a  2  s  .  c o  m*/
    canvas.clipRect(bounds);

    final int span = bounds.right - bounds.left;
    if (span < width) {
        bounds.left = bounds.right - width;
    }

    drawable.setBounds(bounds);
    drawable.draw(canvas);

    canvas.restore();
}

From source file:com.appunite.list.HorizontalListView.java

void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
    final int width = drawable.getMinimumWidth();

    canvas.save();//from  ww  w .j a v  a2  s.  c om
    canvas.clipRect(bounds);

    final int span = bounds.right - bounds.left;
    if (span < width) {
        bounds.right = bounds.left + width;
    }

    drawable.setBounds(bounds);
    drawable.draw(canvas);

    canvas.restore();
}

From source file:com.appunite.list.ListView.java

void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
    final int height = drawable.getMinimumHeight();

    canvas.save();/*  ww  w . j a  v a 2  s.co m*/
    canvas.clipRect(bounds);

    final int span = bounds.bottom - bounds.top;
    if (span < height) {
        bounds.top = bounds.bottom - height;
    }

    drawable.setBounds(bounds);
    drawable.draw(canvas);

    canvas.restore();
}

From source file:com.appunite.list.ListView.java

void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
    final int height = drawable.getMinimumHeight();

    canvas.save();/*ww  w.  ja va  2  s .c  o m*/
    canvas.clipRect(bounds);

    final int span = bounds.bottom - bounds.top;
    if (span < height) {
        bounds.bottom = bounds.top + height;
    }

    drawable.setBounds(bounds);
    drawable.draw(canvas);

    canvas.restore();
}