Example usage for android.graphics.drawable Drawable getIntrinsicHeight

List of usage examples for android.graphics.drawable Drawable getIntrinsicHeight

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable getIntrinsicHeight.

Prototype

public int getIntrinsicHeight() 

Source Link

Document

Returns the drawable's intrinsic height.

Usage

From source file:com.findcab.activity.LocationOverlay.java

/**
 * ?//from www. ja v a2 s  .  c om
 * 
 * @param isDisplay
 */
private void displayDrivers(boolean isDisplay) {

    if (isDisplay) {

        Drawable marker = getResources().getDrawable(R.drawable.cear);
        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());

        for (int i = 0; i < mGeoList.size(); i++) {
            System.out.println("??mGeoList---------->" + mGeoList.get(i).getTitle());
        }

        // for (int i = 1; i < mGeoList.size(); i++) {
        // mGeoList.remove(i);
        // }
        mGeoList.clear();
        OverlayItem item1 = new OverlayItem(new GeoPoint((int) (lat * 1e6), (int) (lng * 1e6)), "", "");

        Drawable maker1 = getResources().getDrawable(R.drawable.person);
        item1.setMarker(maker1);
        mGeoList.add(item1);
        for (int i = 0; i < mGeoList.size(); i++) {
            System.out.println("mGeoList---------->" + mGeoList.get(i).getTitle());
        }

        int size = driversList.size();
        OverlayItem item = null;
        double driverLat, driverLng;
        DriversInfo drivers;
        Drawable maker = getResources().getDrawable(R.drawable.cear);

        for (int i = 0; i < size; i++) {
            drivers = driversList.get(i);
            driverLat = drivers.getLat();
            driverLng = drivers.getLng();

            item = new OverlayItem(new GeoPoint((int) (driverLat * 1e6), (int) (driverLng * 1e6)),
                    drivers.getName(), " ");
            item.setMarker(maker);
            mGeoList.add(item);
        }

        for (int i = 0; i < mGeoList.size(); i++) {
            System.out.println("??mGeoList---------->" + mGeoList.get(i).getTitle());
        }

        MyItemizedOverlay overlay = new MyItemizedOverlay(context, maker, mGeoList, driversList);

        mMapView.getOverlays().clear();// ??mGeoList
        for (int i = 0; i < mGeoList.size(); i++) {
            System.out.println("cleae?mGeoList---------->" + mGeoList.get(i).getTitle());
        }
        mMapView.getOverlays().add(0, overlay);
        for (int i = 0; i < mGeoList.size(); i++) {
            System.out.println("add?mGeoList---------->" + mGeoList.get(i).getTitle());
        }
        mMapView.refresh();
    }
}

From source file:com.scoreflex.ScoreflexView.java

/**
 * The constructor of the view.//from  w w w  .ja  v  a 2 s  .co  m
 * @param activity The activity holding the view.
 * @param attrs
 * @param defStyle
 */
@SuppressWarnings("deprecation")
public ScoreflexView(Activity activity, AttributeSet attrs, int defStyle) {
    super(activity, attrs, defStyle);

    // Keep a reference on the activity
    mParentActivity = activity;

    // Default layout params
    if (null == getLayoutParams()) {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                Scoreflex.getDensityIndependantPixel(R.dimen.scoreflex_panel_height)));
    }

    // Set our background color
    setBackgroundColor(getContext().getResources().getColor(R.color.scoreflex_background_color));

    // Create the top bar
    View topBar = new View(getContext());
    topBar.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            getResources().getDimensionPixelSize(R.dimen.scoreflex_topbar_height), Gravity.TOP));
    topBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.scoreflex_gradient_background));
    addView(topBar);

    // Create the retry button
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mErrorLayout = (ViewGroup) inflater.inflate(R.layout.scoreflex_error_layout, null);
    if (mErrorLayout != null) {

        // Configure refresh button
        Button refreshButton = (Button) mErrorLayout.findViewById(R.id.scoreflex_retry_button);
        if (null != refreshButton) {
            refreshButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    if (null == Scoreflex.getPlayerId()) {
                        setUserInterfaceState(new LoadingState());
                        loadUrlAfterLoggedIn(mInitialResource, mInitialRequestParams);
                    } else if (null == mWebView.getUrl()) {
                        setResource(mInitialResource);
                    } else {
                        mWebView.reload();
                    }
                }
            });
        }

        // Configure cancel button
        Button cancelButton = (Button) mErrorLayout.findViewById(R.id.scoreflex_cancel_button);
        if (null != cancelButton) {
            cancelButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    close();
                }
            });
        }

        // Get hold of the message view
        mMessageView = (TextView) mErrorLayout.findViewById(R.id.scoreflex_error_message_view);
        addView(mErrorLayout);

    }

    // Create the close button
    mCloseButton = new ImageButton(getContext());
    Drawable closeButtonDrawable = getResources().getDrawable(R.drawable.scoreflex_close_button);
    int closeButtonMargin = (int) ((getResources().getDimensionPixelSize(R.dimen.scoreflex_topbar_height)
            - closeButtonDrawable.getIntrinsicHeight()) / 2.0f);
    FrameLayout.LayoutParams closeButtonLayoutParams = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
            Gravity.TOP | Gravity.RIGHT);
    closeButtonLayoutParams.setMargins(0, closeButtonMargin, closeButtonMargin, 0);
    mCloseButton.setLayoutParams(closeButtonLayoutParams);
    mCloseButton.setImageDrawable(closeButtonDrawable);
    mCloseButton.setBackgroundDrawable(null);
    mCloseButton.setPadding(0, 0, 0, 0);
    mCloseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            close();
        }
    });
    addView(mCloseButton);

    // Create the web view
    mWebView = new WebView(mParentActivity);
    mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    // mWebView.setBackgroundColor(Color.RED);
    mWebView.setWebViewClient(new ScoreflexWebViewClient());
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d("Scoreflex", "javascript Error: "
                    + String.format("%s @ %d: %s", cm.message(), cm.lineNumber(), cm.sourceId()));
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            // mtbActivity.mUploadMessage = uploadMsg;
            mUploadMessage = uploadMsg;

            String fileName = "picture.jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            // mOutputFileUri = mParentActivity.getContentResolver().insert(
            // MediaStore.Images.Media.DATA, values);
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = mParentActivity.getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                cameraIntents.add(intent);
            }

            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source please");

            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {}));

            mParentActivity.startActivityForResult(chooserIntent, Scoreflex.FILECHOOSER_RESULTCODE);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg);
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setDatabasePath(
            getContext().getFilesDir().getPath() + "/data/" + getContext().getPackageName() + "/databases/");
    addView(mWebView);

    TypedArray a = mParentActivity.obtainStyledAttributes(attrs, R.styleable.ScoreflexView, defStyle, 0);
    String resource = a.getString(R.styleable.ScoreflexView_resource);
    if (null != resource)
        setResource(resource);

    a.recycle();

    // Create the animated spinner

    mProgressBar = (ProgressBar) ((LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.scoreflex_progress_bar, null);
    mProgressBar.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
    addView(mProgressBar);
    LocalBroadcastManager.getInstance(activity).registerReceiver(mLoginReceiver,
            new IntentFilter(Scoreflex.INTENT_USER_LOGED_IN));
    setUserInterfaceState(new InitialState());
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

private void setButtonImages(View view, BrowserButton buttonProps, int disabledAlpha) {
    Drawable normalDrawable = null;
    Drawable disabledDrawable = null;//from w w  w  .  jav  a  2 s.  c om
    Drawable pressedDrawable = null;

    CharSequence description = view.getContentDescription();

    if (buttonProps.image != null || buttonProps.wwwImage != null) {
        try {
            normalDrawable = getImage(buttonProps.image, buttonProps.wwwImage, buttonProps.wwwImageDensity);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.width = normalDrawable.getIntrinsicWidth();
            params.height = normalDrawable.getIntrinsicHeight();
        } catch (Resources.NotFoundException e) {
            emitError(ERR_LOADFAIL,
                    String.format("Image for %s, %s, failed to load", description, buttonProps.image));
        } catch (IOException ioe) {
            emitError(ERR_LOADFAIL,
                    String.format("Image for %s, %s, failed to load", description, buttonProps.wwwImage));
        }
    } else {
        emitWarning(WRN_UNDEFINED,
                String.format("Image for %s is not defined. Button will not be shown", description));
    }

    if (buttonProps.imagePressed != null || buttonProps.wwwImagePressed != null) {
        try {
            pressedDrawable = getImage(buttonProps.imagePressed, buttonProps.wwwImagePressed,
                    buttonProps.wwwImageDensity);
        } catch (Resources.NotFoundException e) {
            emitError(ERR_LOADFAIL, String.format("Pressed image for %s, %s, failed to load", description,
                    buttonProps.imagePressed));
        } catch (IOException e) {
            emitError(ERR_LOADFAIL, String.format("Pressed image for %s, %s, failed to load", description,
                    buttonProps.wwwImagePressed));
        }
    } else {
        emitWarning(WRN_UNDEFINED, String.format("Pressed image for %s is not defined.", description));
    }

    if (normalDrawable != null) {
        // Create the disabled state drawable by fading the normal state
        // drawable. Drawable.setAlpha() stopped working above Android 4.4
        // so we gotta bring out some bitmap magic. Credit goes to:
        // http://stackoverflow.com/a/7477572
        Bitmap enabledBitmap = ((BitmapDrawable) normalDrawable).getBitmap();
        Bitmap disabledBitmap = Bitmap.createBitmap(normalDrawable.getIntrinsicWidth(),
                normalDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(disabledBitmap);

        Paint paint = new Paint();
        paint.setAlpha(disabledAlpha);
        canvas.drawBitmap(enabledBitmap, 0, 0, paint);

        Resources activityRes = cordova.getActivity().getResources();
        disabledDrawable = new BitmapDrawable(activityRes, disabledBitmap);
    }

    StateListDrawable states = new StateListDrawable();
    if (pressedDrawable != null) {
        states.addState(new int[] { android.R.attr.state_pressed }, pressedDrawable);
    }
    if (normalDrawable != null) {
        states.addState(new int[] { android.R.attr.state_enabled }, normalDrawable);
    }
    if (disabledDrawable != null) {
        states.addState(new int[] {}, disabledDrawable);
    }

    setBackground(view, states);
}

From source file:com.hippo.ehviewer.ui.scene.GalleryDetailScene.java

@Nullable
@Override//from  ww  w .ja v  a  2 s .  c o  m
public View onCreateView2(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    // Get download state
    long gid = getGid();
    if (gid != -1) {
        Context context = getContext2();
        Assert.assertNotNull(context);
        mDownloadState = EhApplication.getDownloadManager(context).getDownloadState(gid);
    } else {
        mDownloadState = DownloadInfo.STATE_INVALID;
    }

    View view = inflater.inflate(R.layout.scene_gallery_detail, container, false);

    ViewGroup main = (ViewGroup) ViewUtils.$$(view, R.id.main);
    View mainView = ViewUtils.$$(main, R.id.scroll_view);
    View progressView = ViewUtils.$$(main, R.id.progress_view);
    mTip = (TextView) ViewUtils.$$(main, R.id.tip);
    mViewTransition = new ViewTransition(mainView, progressView, mTip);

    Context context = getContext2();
    Assert.assertNotNull(context);

    Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    mTip.setCompoundDrawables(null, drawable, null, null);
    mTip.setOnClickListener(this);

    mHeader = ViewUtils.$$(mainView, R.id.header);
    mColorBg = ViewUtils.$$(mHeader, R.id.color_bg);
    mThumb = (LoadImageView) ViewUtils.$$(mHeader, R.id.thumb);
    mTitle = (TextView) ViewUtils.$$(mHeader, R.id.title);
    mUploader = (TextView) ViewUtils.$$(mHeader, R.id.uploader);
    mCategory = (TextView) ViewUtils.$$(mHeader, R.id.category);
    mOtherActions = (ImageView) ViewUtils.$$(mHeader, R.id.other_actions);
    mActionGroup = (ViewGroup) ViewUtils.$$(mHeader, R.id.action_card);
    mDownload = (TextView) ViewUtils.$$(mActionGroup, R.id.download);
    mRead = ViewUtils.$$(mActionGroup, R.id.read);
    Ripple.addRipple(mOtherActions, false);
    Ripple.addRipple(mDownload, false);
    Ripple.addRipple(mRead, false);
    mUploader.setOnClickListener(this);
    mCategory.setOnClickListener(this);
    mOtherActions.setOnClickListener(this);
    mDownload.setOnClickListener(this);
    mDownload.setOnLongClickListener(this);
    mRead.setOnClickListener(this);

    mUploader.setOnLongClickListener(this);

    mBelowHeader = mainView.findViewById(R.id.below_header);
    View belowHeader = mBelowHeader;

    mInfo = ViewUtils.$$(belowHeader, R.id.info);
    mLanguage = (TextView) ViewUtils.$$(mInfo, R.id.language);
    mPages = (TextView) ViewUtils.$$(mInfo, R.id.pages);
    mSize = (TextView) ViewUtils.$$(mInfo, R.id.size);
    mPosted = (TextView) ViewUtils.$$(mInfo, R.id.posted);
    mFavoredTimes = (TextView) ViewUtils.$$(mInfo, R.id.favoredTimes);
    Ripple.addRipple(mInfo, false);
    mInfo.setOnClickListener(this);

    mActions = ViewUtils.$$(belowHeader, R.id.actions);
    mRatingText = (TextView) ViewUtils.$$(mActions, R.id.rating_text);
    mRating = (RatingBar) ViewUtils.$$(mActions, R.id.rating);
    mHeartGroup = ViewUtils.$$(mActions, R.id.heart_group);
    mHeart = (TextView) ViewUtils.$$(mHeartGroup, R.id.heart);
    mHeartOutline = (TextView) ViewUtils.$$(mHeartGroup, R.id.heart_outline);
    mTorrent = (TextView) ViewUtils.$$(mActions, R.id.torrent);
    mShare = (TextView) ViewUtils.$$(mActions, R.id.share);
    mRate = (TextView) ViewUtils.$$(mActions, R.id.rate);
    mSimilar = (TextView) ViewUtils.$$(mActions, R.id.similar);
    mSearchCover = (TextView) ViewUtils.$$(mActions, R.id.search_cover);
    Ripple.addRipple(mHeartGroup, false);
    Ripple.addRipple(mTorrent, false);
    Ripple.addRipple(mShare, false);
    Ripple.addRipple(mRate, false);
    Ripple.addRipple(mSimilar, false);
    Ripple.addRipple(mSearchCover, false);
    mHeartGroup.setOnClickListener(this);
    mTorrent.setOnClickListener(this);
    mShare.setOnClickListener(this);
    mRate.setOnClickListener(this);
    mSimilar.setOnClickListener(this);
    mSearchCover.setOnClickListener(this);
    ensureActionDrawable(context);

    mTags = (LinearLayout) ViewUtils.$$(belowHeader, R.id.tags);
    mNoTags = (TextView) ViewUtils.$$(mTags, R.id.no_tags);

    mComments = (LinearLayout) ViewUtils.$$(belowHeader, R.id.comments);
    mCommentsText = (TextView) ViewUtils.$$(mComments, R.id.comments_text);
    Ripple.addRipple(mComments, false);
    mComments.setOnClickListener(this);

    mPreviews = ViewUtils.$$(belowHeader, R.id.previews);
    mGridLayout = (SimpleGridAutoSpanLayout) ViewUtils.$$(mPreviews, R.id.grid_layout);
    mPreviewText = (TextView) ViewUtils.$$(mPreviews, R.id.preview_text);
    Ripple.addRipple(mPreviews, false);
    mPreviews.setOnClickListener(this);

    mProgress = ViewUtils.$$(mainView, R.id.progress);

    mViewTransition2 = new ViewTransition(mBelowHeader, mProgress);

    if (prepareData()) {
        if (mGalleryDetail != null) {
            bindViewSecond();
            setTransitionName();
            adjustViewVisibility(STATE_NORMAL, false);
        } else if (mGalleryInfo != null) {
            bindViewFirst();
            setTransitionName();
            adjustViewVisibility(STATE_REFRESH_HEADER, false);
        } else {
            adjustViewVisibility(STATE_REFRESH, false);
        }
    } else {
        mTip.setText(R.string.error_cannot_find_gallery);
        adjustViewVisibility(STATE_FAILED, false);
    }

    EhApplication.getDownloadManager(context).addDownloadInfoListener(this);

    return view;
}

From source file:org.kde.necessitas.ministro.ExtractStyle.java

public JSONObject getDrawable(Object drawable, String filename) {
    JSONObject json = new JSONObject();
    Bitmap bmp = null;// www.j  a  v a  2 s  .com
    if (drawable instanceof Bitmap)
        bmp = (Bitmap) drawable;
    else {
        if (drawable instanceof BitmapDrawable)
            bmp = ((BitmapDrawable) drawable).getBitmap();
        else {
            if (drawable instanceof LayerDrawable) {
                return getLayerDrawable(drawable, filename);
            }
            if (drawable instanceof StateListDrawable) {
                return getStateListDrawable(drawable, filename);
            }
            if (drawable instanceof GradientDrawable) {
                return getGradientDrawable((GradientDrawable) drawable);
            }
            if (drawable instanceof ClipDrawable) {
                try {
                    json.put("type", "clipDrawable");
                    json.put("drawable",
                            getDrawable(
                                    getClipStateDrawableObject(((ClipDrawable) drawable).getConstantState()),
                                    filename));
                    Rect padding = new Rect();
                    if (((Drawable) drawable).getPadding(padding))
                        json.put("padding", getJsonRect(padding));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return json;
            }
            if (drawable instanceof ColorDrawable) {
                bmp = Bitmap.createBitmap(1, 1, Config.ARGB_8888);
                Drawable d = (Drawable) drawable;
                d.setBounds(0, 0, 1, 1);
                d.draw(new Canvas(bmp));
                Rect padding = new Rect();
                try {
                    json.put("type", "color");
                    json.put("color", bmp.getPixel(0, 0));
                    if (d.getPadding(padding))
                        json.put("padding", getJsonRect(padding));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return json;
            } else {
                Drawable d = (Drawable) drawable;
                int w = d.getIntrinsicWidth();
                int h = d.getIntrinsicHeight();
                d.setLevel(10000);
                if (w < 1 || h < 1) {
                    w = 100;
                    h = 100;
                }
                bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
                d.setBounds(0, 0, w, h);
                d.draw(new Canvas(bmp));
                if (drawable instanceof NinePatchDrawable) {
                    NinePatchDrawable npd = (NinePatchDrawable) drawable;
                    try {
                        json.put("type", "9patch");
                        json.put("drawable", getDrawable(bmp, filename));
                        Rect padding = new Rect();
                        if (npd.getPadding(padding))
                            json.put("padding", getJsonRect(padding));
                        json.put("chunkInfo", findPatchesMarings(d));
                        return json;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    FileOutputStream out;
    try {
        filename = m_extractPath + filename + ".png";
        out = new FileOutputStream(filename);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        json.put("type", "image");
        json.put("path", filename);
        json.put("width", bmp.getWidth());
        json.put("height", bmp.getHeight());
        MinistroActivity.nativeChmode(filename, 0644);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return json;
}

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

private boolean beginDraggingWidget(View v) {
    mDraggingWidget = true;//  w  ww .  ja v a 2 s  .c o m
    // Get the widget preview as the drag representation
    ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
    PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();

    // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
    // we abort the drag.
    if (image.getDrawable() == null) {
        mDraggingWidget = false;
        return false;
    }

    // Compose the drag image
    Bitmap preview;
    Bitmap outline;
    float scale = 1f;
    if (createItemInfo instanceof PendingAddWidgetInfo) {
        // This can happen in some weird cases involving multi-touch. We can't start dragging
        // the widget if this is null, so we break out.
        if (mCreateWidgetInfo == null) {
            return false;
        }

        PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
        createItemInfo = createWidgetInfo;
        int spanX = createItemInfo.spanX;
        int spanY = createItemInfo.spanY;
        int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY, createWidgetInfo, true);

        FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
        float minScale = 1.25f;
        int maxWidth, maxHeight;
        maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
        maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
        preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
                createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);

        // Determine the image view drawable scale relative to the preview
        float[] mv = new float[9];
        Matrix m = new Matrix();
        m.setRectToRect(new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
                new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
                        (float) previewDrawable.getIntrinsicHeight()),
                Matrix.ScaleToFit.START);
        m.getValues(mv);
        scale = (float) mv[0];
    } else {
        PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
        Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
        preview = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);

        mCanvas.setBitmap(preview);
        mCanvas.save();
        renderDrawableToBitmap(icon, preview, 0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
        mCanvas.restore();
        mCanvas.setBitmap(null);
        createItemInfo.spanX = createItemInfo.spanY = 1;
    }

    // Don't clip alpha values for the drag outline if we're using the default widget preview
    boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo
            && (((PendingAddWidgetInfo) createItemInfo).previewImage == 0));

    // Save the preview for the outline generation, then dim the preview
    outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(), false);

    // Start the drag
    mLauncher.lockScreenOrientation();
    mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, clipAlpha);
    mDragController.startDrag(image, preview, this, createItemInfo, DragController.DRAG_ACTION_COPY, null,
            scale);
    outline.recycle();
    preview.recycle();
    return true;
}

From source file:cnedu.ustcjd.widget.MultiSlider.java

/**
 * @param gap If set to {@link Integer#MIN_VALUE}, this will be ignored and
 *///  ww  w .jav  a 2s.c  o  m
private void setThumbPos(int w, int h, Drawable thumb, Drawable prevThumb, Drawable range, float scale, int gap,
        int thumbOffset, int optThumbOffset) {
    final int available = getAvailable();
    int thumbWidth = thumb.getIntrinsicWidth();
    int thumbHeight = thumb.getIntrinsicHeight();
    int prevLeft = thumb.getBounds().left;

    //todo change available before also

    float scaleOffset = getScaleSize() > 0 ? (float) mScaleMin / (float) getScaleSize() : 0;

    int thumbPos = (int) (scale * available - scaleOffset * available + 0.5f);

    int topBound, bottomBound;
    if (gap == Integer.MIN_VALUE) {
        Rect oldBounds = thumb.getBounds();
        topBound = oldBounds.top;
        bottomBound = oldBounds.bottom;
    } else {
        topBound = gap;
        bottomBound = gap + thumbHeight;
    }

    // Canvas will be translated, so 0,0 is where we start drawing
    final int left = (isLayoutRtl() && mMirrorForRtl) ? available - thumbPos - optThumbOffset
            : thumbPos + optThumbOffset;

    thumb.setBounds(left, topBound, left + thumbWidth, bottomBound);

    w -= getPaddingRight() + getPaddingLeft();
    h -= getPaddingTop() + getPaddingBottom();

    int right = w;
    int bottom = h;

    int leftRange = 0;
    if (prevThumb != null) {
        leftRange = prevThumb.getBounds().left;
    }
    if (range != null) {
        range.setBounds(leftRange, 0, left, bottom);
    }

    invalidate();
}

From source file:io.apptik.widget.MultiSlider.java

/**
 * Sets the thumb drawable for all thumbs
 * <p/>/*from ww  w .  j a v  a2  s .  c o  m*/
 * If the thumb is a valid drawable (i.e. not null), half its width will be
 * used as the new thumb offset (@see #setThumbOffset(int)).
 *
 * @param thumb Drawable representing the thumb
 */
private void setThumbDrawables(Drawable thumb, Drawable range, Drawable range1, Drawable range2) {
    if (thumb == null)
        return;
    boolean needUpdate;
    Drawable rangeDrawable;

    // This way, calling setThumbDrawables again with the same bitmap will result in
    // it recalculating thumbOffset (if for example it the bounds of the
    // drawable changed)
    int curr = 0;
    int padding = 0;
    for (Thumb mThumb : mThumbs) {
        curr++;
        if (mThumb.getThumb() != null && thumb != mThumb.getThumb()) {
            mThumb.getThumb().setCallback(null);
            needUpdate = true;
        } else {
            needUpdate = false;
        }

        if (curr == 1 && range1 != null) {
            rangeDrawable = getTintedDrawable(range1,
                    a.getColor(io.apptik.widget.R.styleable.MultiSlider_range1Color, 0));
        } else if (curr == 2 && range2 != null) {
            rangeDrawable = getTintedDrawable(range2,
                    a.getColor(io.apptik.widget.R.styleable.MultiSlider_range2Color, 0));
        } else {
            rangeDrawable = getTintedDrawable(range.getConstantState().newDrawable(),
                    a.getColor(io.apptik.widget.R.styleable.MultiSlider_rangeColor, 0));
        }

        mThumb.setRange(rangeDrawable);

        Drawable newDrawable = getTintedDrawable(thumb.getConstantState().newDrawable(),
                a.getColor(io.apptik.widget.R.styleable.MultiSlider_thumbColor, 0));
        newDrawable.setCallback(this);

        // Assuming the thumb drawable is symmetric, set the thumb offset
        // such that the thumb will hang halfway off either edge of the
        // progress bar.
        mThumb.setThumbOffset(thumb.getIntrinsicWidth() / 2);

        padding = Math.max(padding, mThumb.getThumbOffset());
        // If we're updating get the new states
        if (needUpdate && (newDrawable.getIntrinsicWidth() != mThumb.getThumb().getIntrinsicWidth()
                || newDrawable.getIntrinsicHeight() != mThumb.getThumb().getIntrinsicHeight())) {
            requestLayout();
        }
        mThumb.setThumb(newDrawable);

        if (needUpdate) {
            invalidate();
            if (thumb != null && thumb.isStateful()) {
                // Note that if the states are different this won't work.
                // For now, let's consider that an app bug.
                int[] state = getDrawableState();
                thumb.setState(state);
            }

        }
    }
    setPadding(padding, getPaddingTop(), padding, getPaddingBottom());

}

From source file:com.android.launcher3.Utilities.java

/**
 * @param scale the scale to apply before drawing {@param icon} on the canvas
 *///w  ww  .  j  a v  a 2s  .co  m
public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
    synchronized (sCanvas) {
        final int iconBitmapSize = getIconBitmapSize();

        int width = iconBitmapSize;
        int height = iconBitmapSize;

        if (icon instanceof PaintDrawable) {
            PaintDrawable painter = (PaintDrawable) icon;
            painter.setIntrinsicWidth(width);
            painter.setIntrinsicHeight(height);
        } else if (icon instanceof BitmapDrawable) {
            // Ensure the bitmap has a density.
            BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
                bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
            }
        }
        int sourceWidth = icon.getIntrinsicWidth();
        int sourceHeight = icon.getIntrinsicHeight();
        if (sourceWidth > 0 && sourceHeight > 0) {
            // Scale the icon proportionally to the icon dimensions
            final float ratio = (float) sourceWidth / sourceHeight;
            if (sourceWidth > sourceHeight) {
                height = (int) (width / ratio);
            } else if (sourceHeight > sourceWidth) {
                width = (int) (height * ratio);
            }
        }

        // no intrinsic size --> use default size
        int textureWidth = iconBitmapSize;
        int textureHeight = iconBitmapSize;

        final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight, Bitmap.Config.ARGB_8888);
        final Canvas canvas = sCanvas;
        canvas.setBitmap(bitmap);

        final int left = (textureWidth - width) / 2;
        final int top = (textureHeight - height) / 2;

        @SuppressWarnings("all") // suppress dead code warning
        final boolean debug = false;
        if (debug) {
            // draw a big box for the icon for debugging
            canvas.drawColor(sColors[sColorIndex]);
            if (++sColorIndex >= sColors.length)
                sColorIndex = 0;
            Paint debugPaint = new Paint();
            debugPaint.setColor(0xffcccc00);
            canvas.drawRect(left, top, left + width, top + height, debugPaint);
        }

        sOldBounds.set(icon.getBounds());
        icon.setBounds(left, top, left + width, top + height);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
        icon.draw(canvas);
        canvas.restore();
        icon.setBounds(sOldBounds);
        canvas.setBitmap(null);

        return bitmap;
    }
}

From source file:io.jawg.osmcontributor.ui.fragments.MapFragment.java

private void instantiateLevelBar() {
    Drawable d = ContextCompat.getDrawable(getActivity(), R.drawable.level_thumb);
    levelBar.setThumb(d);//from w w w .  j  av  a 2 s .  c om
    levelBar.setDrawableHeight(d.getIntrinsicHeight());
    levelBar.setLevel(currentLevel);
    levelBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            Timber.v("onProgressChanged");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
}