Example usage for android.graphics Paint setAlpha

List of usage examples for android.graphics Paint setAlpha

Introduction

In this page you can find the example usage for android.graphics Paint setAlpha.

Prototype

public void setAlpha(int a) 

Source Link

Document

Helper to setColor(), that only assigns the color's alpha value, leaving its r,g,b values unchanged.

Usage

From source file:net.droidsolutions.droidcharts.core.renderer.xy.AbstractXYItemRenderer.java

/**
 * Draws a horizontal line across the chart to represent a 'range marker'.
 *
 * @param g2  the graphics device.//from  w ww.  ja  v  a  2s .c o m
 * @param plot  the plot.
 * @param rangeAxis  the range axis.
 * @param marker  the marker line.
 * @param dataArea  the axis data area.
 */
public void drawRangeMarker(Canvas g2, XYPlot plot, ValueAxis rangeAxis, Marker marker, Rectangle2D dataArea) {

    if (marker instanceof ValueMarker) {
        ValueMarker vm = (ValueMarker) marker;
        double value = vm.getValue();
        Range range = rangeAxis.getRange();
        if (!range.contains(value)) {
            return;
        }

        double v = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());
        PlotOrientation orientation = plot.getOrientation();
        Line2D line = null;
        if (orientation == PlotOrientation.HORIZONTAL) {
            line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
        } else if (orientation == PlotOrientation.VERTICAL) {
            line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
        }

        Paint oPiant = marker.getPaint();
        oPiant.setStyle(Paint.Style.STROKE);
        int oOldAlpha = oPiant.getAlpha();
        oPiant.setAlpha(marker.getAlpha());
        oPiant.setStrokeWidth(marker.getStroke());
        g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(), (float) line.getY2(),
                oPiant);
        oPiant.setAlpha(oOldAlpha);
        String label = marker.getLabel();
        RectangleAnchor anchor = marker.getLabelAnchor();
        if (label != null) {
            Font labelFont = marker.getLabelFont();
            Paint paint = marker.getLabelPaint();
            paint.setTypeface(labelFont.getTypeFace());
            paint.setTextSize(labelFont.getSize());
            Point2D coordinates = calculateRangeMarkerTextAnchorPoint(g2, orientation, dataArea,
                    line.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
            TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(),
                    marker.getLabelTextAnchor(), paint);
        }

    } else if (marker instanceof IntervalMarker) {
        IntervalMarker im = (IntervalMarker) marker;
        double start = im.getStartValue();
        double end = im.getEndValue();
        Range range = rangeAxis.getRange();
        if (!(range.intersects(start, end))) {
            return;
        }

        double start2d = rangeAxis.valueToJava2D(start, dataArea, plot.getRangeAxisEdge());
        double end2d = rangeAxis.valueToJava2D(end, dataArea, plot.getRangeAxisEdge());
        double low = Math.min(start2d, end2d);
        double high = Math.max(start2d, end2d);

        PlotOrientation orientation = plot.getOrientation();
        Rectangle2D rect = null;
        if (orientation == PlotOrientation.HORIZONTAL) {
            // clip left and right bounds to data area
            low = Math.max(low, dataArea.getMinX());
            high = Math.min(high, dataArea.getMaxX());
            rect = new Rectangle2D.Double(low, dataArea.getMinY(), high - low, dataArea.getHeight());
        } else if (orientation == PlotOrientation.VERTICAL) {
            // clip top and bottom bounds to data area
            low = Math.max(low, dataArea.getMinY());
            high = Math.min(high, dataArea.getMaxY());
            rect = new Rectangle2D.Double(dataArea.getMinX(), low, dataArea.getWidth(), high - low);
        }

        Paint p = marker.getPaint();
        int oldAlpha = p.getAlpha();
        p.setAlpha(marker.getAlpha());
        p.setStyle(Paint.Style.FILL);

        g2.drawRect((float) rect.getMinX(), (float) rect.getMinY(), (float) rect.getMaxX(),
                (float) rect.getMaxY(), p);
        p.setAlpha(oldAlpha);

        // now draw the outlines, if visible...
        if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) {
            if (orientation == PlotOrientation.VERTICAL) {
                Line2D line = new Line2D.Double();
                double x0 = dataArea.getMinX();
                double x1 = dataArea.getMaxX();
                Paint oPiant = im.getOutlinePaint();
                oPiant.setStyle(Paint.Style.STROKE);
                int oOldAlpha = oPiant.getAlpha();
                oPiant.setAlpha(marker.getAlpha());
                oPiant.setStrokeWidth(im.getOutlineStroke());
                if (range.contains(start)) {
                    line.setLine(x0, start2d, x1, start2d);
                    g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(),
                            (float) line.getY2(), oPiant);
                }
                if (range.contains(end)) {
                    line.setLine(x0, end2d, x1, end2d);
                    g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(),
                            (float) line.getY2(), oPiant);
                }
                oPiant.setAlpha(oOldAlpha);
            } else { // PlotOrientation.HORIZONTAL
                Line2D line = new Line2D.Double();
                double y0 = dataArea.getMinY();
                double y1 = dataArea.getMaxY();
                Paint oPiant = im.getOutlinePaint();
                oPiant.setStyle(Paint.Style.STROKE);
                int oOldAlpha = oPiant.getAlpha();
                oPiant.setAlpha(marker.getAlpha());
                oPiant.setStrokeWidth(im.getOutlineStroke());
                if (range.contains(start)) {
                    line.setLine(start2d, y0, start2d, y1);
                    g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(),
                            (float) line.getY2(), oPiant);
                }
                if (range.contains(end)) {
                    line.setLine(end2d, y0, end2d, y1);
                    g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(),
                            (float) line.getY2(), oPiant);
                }
                oPiant.setAlpha(oOldAlpha);
            }
        }

        String label = marker.getLabel();
        RectangleAnchor anchor = marker.getLabelAnchor();
        if (label != null) {
            Font labelFont = marker.getLabelFont();

            Paint paint = marker.getLabelPaint();
            paint.setTypeface(labelFont.getTypeFace());
            paint.setTextSize(labelFont.getSize());
            Point2D coordinates = calculateRangeMarkerTextAnchorPoint(g2, orientation, dataArea, rect,
                    marker.getLabelOffset(), marker.getLabelOffsetType(), anchor);
            TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(),
                    marker.getLabelTextAnchor(), paint);
        }
    }
}

From source file:io.doist.datetimepicker.time.RadialTimePickerView.java

/**
 * Draw the 12 text values at the positions specified by the textGrid parameters.
 *//*from   w  w  w  .  ja v  a  2s. c o  m*/
private void drawTextElements(Canvas canvas, float textSize, Typeface typeface, String[] texts,
        float[] textGridWidths, float[] textGridHeights, Paint paint, int color, int alpha) {
    paint.setTextSize(textSize);
    paint.setTypeface(typeface);
    paint.setColor(color);
    paint.setAlpha(getMultipliedAlpha(color, alpha));
    canvas.drawText(texts[0], textGridWidths[3], textGridHeights[0], paint);
    canvas.drawText(texts[1], textGridWidths[4], textGridHeights[1], paint);
    canvas.drawText(texts[2], textGridWidths[5], textGridHeights[2], paint);
    canvas.drawText(texts[3], textGridWidths[6], textGridHeights[3], paint);
    canvas.drawText(texts[4], textGridWidths[5], textGridHeights[4], paint);
    canvas.drawText(texts[5], textGridWidths[4], textGridHeights[5], paint);
    canvas.drawText(texts[6], textGridWidths[3], textGridHeights[6], paint);
    canvas.drawText(texts[7], textGridWidths[2], textGridHeights[5], paint);
    canvas.drawText(texts[8], textGridWidths[1], textGridHeights[4], paint);
    canvas.drawText(texts[9], textGridWidths[0], textGridHeights[3], paint);
    canvas.drawText(texts[10], textGridWidths[1], textGridHeights[2], paint);
    canvas.drawText(texts[11], textGridWidths[2], textGridHeights[1], paint);
}

From source file:net.toload.main.hd.candidate.CandidateView.java

private void doDraw(Canvas canvas) {

    if (mSuggestions == null)
        return;/* w w w  .j  a v  a  2 s . c om*/
    if (DEBUG)
        Log.i(TAG, "CandidateView:doDraw():Suggestion mCount:" + mCount + " mSuggestions.size:"
                + mSuggestions.size());
    mTotalWidth = 0;

    updateFontSize();

    if (mBgPadding == null) {
        mBgPadding = new Rect(0, 0, 0, 0);
        if (getBackground() != null) {
            getBackground().getPadding(mBgPadding);
        }
    }

    final int height = mHeight;
    final Rect bgPadding = mBgPadding;
    final Paint candidatePaint = mCandidatePaint;
    final Paint candidateEmojiPaint = mCandidatePaint;
    candidateEmojiPaint.setTextSize((float) (candidateEmojiPaint.getTextSize() * 0.9));

    final Paint selKeyPaint = mSelKeyPaint;
    final int touchX = mTouchX;
    final int scrollX = getScrollX();
    final boolean scrolled = mScrolled;

    final int textBaseLine = (int) (((height - mCandidatePaint.getTextSize()) / 2) - mCandidatePaint.ascent());

    // Modified by jeremy '10, 3, 29.  Update mselectedindex if touched and build wordX[i] and wordwidth[i]
    int x = 0;
    final int count = mCount; //Cache count here '11,8,18
    for (int i = 0; i < count; i++) {
        if (count != mCount || mSuggestions == null || count != mSuggestions.size() || mSuggestions.size() == 0
                || i >= mSuggestions.size())
            return; // mSuggestion is updated, force abort

        String suggestion = mSuggestions.get(i).getWord();
        if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord()
                && suggestion.length() > 8) {
            suggestion = suggestion.substring(0, 2) + "..";
        }
        float base = (suggestion == null) ? 0 : candidatePaint.measureText("");
        float textWidth = (suggestion == null) ? 0 : candidatePaint.measureText(suggestion);

        if (textWidth < base) {
            textWidth = base;
        }

        final int wordWidth = (int) textWidth + X_GAP * 2;

        mWordX[i] = x;

        mWordWidth[i] = wordWidth;

        if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) {
            mSelectedIndex = i;
        }
        x += wordWidth;
    }

    mTotalWidth = x;

    if (DEBUG)
        Log.i(TAG,
                "CandidateView:doDraw():mTotalWidth :" + mTotalWidth + "  this.getWidth():" + this.getWidth());

    //Jeremy '11,8,11. If the candidate list is within 1 page and has more records, get full records first.
    if (mTotalWidth < this.getWidth())
        checkHasMoreRecords();

    // Paint all the suggestions and lines.
    if (canvas != null) {

        // Moved from above by jeremy '10 3, 29. Paint mSelectedindex in highlight here
        if (count > 0 && mSelectedIndex >= 0) {
            //    candidatePaint.setColor(mColorComposingCode);
            //    canvas.drawRect(mWordX[mSelectedIndex],bgPadding.top, mWordWidth[mSelectedIndex] , height, candidatePaint);

            canvas.translate(mWordX[mSelectedIndex], 0);
            mDrawableSuggestHighlight.setBounds(0, bgPadding.top, mWordWidth[mSelectedIndex], height);
            mDrawableSuggestHighlight.draw(canvas);
            canvas.translate(-mWordX[mSelectedIndex], 0);

        }
        if (mTransparentCandidateView) {
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

            Paint backgroundPaint = new Paint();
            backgroundPaint.setColor(ContextCompat.getColor(mContext, R.color.third_background_light));
            backgroundPaint.setAlpha(33);
            backgroundPaint.setStyle(Paint.Style.FILL);

            canvas.drawRect(0.5f, bgPadding.top, mScreenWidth, height, backgroundPaint);
        }

        for (int i = 0; i < count; i++) {

            if (count != mCount || mSuggestions == null || count != mSuggestions.size()
                    || mSuggestions.size() == 0 || i >= mSuggestions.size())
                break;

            boolean isEmoji = mSuggestions.get(i).isEmojiRecord();
            String suggestion = mSuggestions.get(i).getWord();
            if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord()
                    && suggestion.length() > 8) {
                suggestion = suggestion.substring(0, 2) + "..";
            }

            int c = i + 1;
            switch (mSuggestions.get(i).getRecordType()) {
            case Mapping.RECORD_COMPOSING_CODE:
                if (mSelectedIndex == 0) {

                    if (mTransparentCandidateView) {
                        candidatePaint.setColor(mColorInvertedTextTransparent);
                    } else {
                        candidatePaint.setColor(mColorComposingCodeHighlight);
                    }
                } else
                    candidatePaint.setColor(mColorComposingCode);
                break;
            case Mapping.RECORD_CHINESE_PUNCTUATION_SYMBOL:
            case Mapping.RECORD_RELATED_PHRASE:
                selKeyPaint.setColor(mColorSelKeyShifted);
                if (i == mSelectedIndex)
                    candidatePaint.setColor(mColorNormalTextHighlight);
                else
                    candidatePaint.setColor(mColorNormalText);
                break;
            case Mapping.RECORD_EXACT_MATCH_TO_CODE:
            case Mapping.RECORD_PARTIAL_MATCH_TO_CODE:
            case Mapping.RECORD_RUNTIME_BUILT_PHRASE:
            case Mapping.RECORD_ENGLISH_SUGGESTION:
            default:
                selKeyPaint.setColor(mColorSelKey);
                if (i == mSelectedIndex)
                    candidatePaint.setColor(mColorNormalTextHighlight);
                else
                    candidatePaint.setColor(mColorNormalText);
                break;

            }

            if (isEmoji) {
                canvas.drawText(suggestion, mWordX[i] + X_GAP, Math.round(textBaseLine * 0.95),
                        candidateEmojiPaint);
            } else {
                canvas.drawText(suggestion, mWordX[i] + X_GAP, textBaseLine, candidatePaint);
            }
            if (mShowNumber) {
                //Jeremy '11,6,17 changed from <=10 to mDisplaySelkey length. The length maybe 11 or 12 if shifted with space.
                if (c <= mDisplaySelkey.length()) {
                    //Jeremy '11,6,11 Drawing text using relative font dimensions.
                    canvas.drawText(mDisplaySelkey.substring(c - 1, c),
                            mWordX[i] + mWordWidth[i] - height * 0.3f, height * 0.4f, selKeyPaint);
                }
            }
            //Draw spacer
            candidatePaint.setColor(mColorSpacer);
            canvas.drawLine(mWordX[i] + mWordWidth[i] + 0.5f, bgPadding.top + (mVerticalPadding / 2),
                    mWordX[i] + mWordWidth[i] + 0.5f, height - (mVerticalPadding / 2), candidatePaint);
            candidatePaint.setFakeBoldText(false);

        }

        if (mTargetScrollX != getScrollX()) {
            if (DEBUG)
                Log.i(TAG, "CandidateView:doDraw():mTargetScrollX :" + mTargetScrollX + "  getScrollX():"
                        + getScrollX());
            scrollToTarget();
        }

    }

}

From source file:radialdemo.RadialMenuWidget.java

@Override
protected void onDraw(Canvas c) {

    Paint paint = new Paint();
    paint.setAntiAlias(true);//from   ww  w.ja  v  a2s  . co  m
    paint.setStrokeWidth(3);

    // draws a dot at the source of the press
    if (showSource == true) {
        paint.setColor(outlineColor);
        paint.setAlpha(outlineAlpha);
        paint.setStyle(Paint.Style.STROKE);
        c.drawCircle(xSource, ySource, cRadius / 10, paint);

        paint.setColor(selectedColor);
        paint.setAlpha(selectedAlpha);
        paint.setStyle(Paint.Style.FILL);
        c.drawCircle(xSource, ySource, cRadius / 10, paint);
    }
    //inner
    for (int i = 0; i < Wedges.length; i++) {
        RadialMenuWedge f = Wedges[i];
        paint.setColor(outlineColor);
        paint.setAlpha(outlineAlpha);
        paint.setStyle(Paint.Style.STROKE);
        c.drawPath(f, paint);
        if (f == enabled && Wedge2Shown == true) {
            paint.setColor(wedge2Color);
            paint.setAlpha(wedge2Alpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawPath(f, paint);
        } else if (f != enabled && Wedge2Shown == true) {
            paint.setColor(disabledColor);
            paint.setAlpha(disabledAlpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawPath(f, paint);
        } else if (f == enabled && Wedge2Shown == false) {
            paint.setColor(wedge2Color);
            paint.setAlpha(wedge2Alpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawPath(f, paint);
        } else if (f == selected) {
            paint.setColor(wedge2Color);
            paint.setAlpha(wedge2Alpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawPath(f, paint);
        } else {
            paint.setColor(defaultColor);
            paint.setAlpha(defaultAlpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawPath(f, paint);
        }
        //button content
        Rect rf = iconRect[i];

        if ((menuEntries.get(i).getIcon() != 0) && (menuEntries.get(i).getLabel() != null)) {

            // This will look for a "new line" and split into multiple lines
            String menuItemName = menuEntries.get(i).getLabel();
            String[] stringArray = menuItemName.split("\n");

            paint.setColor(textColor);
            if (f != enabled && Wedge2Shown == true) {
                paint.setAlpha(disabledAlpha);
            } else {
                paint.setAlpha(textAlpha);
            }
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(textSize);

            Rect rect = new Rect();
            float textHeight = 0;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                textHeight = textHeight + (rect.height() + 3);
            }

            Rect rf2 = new Rect();
            rf2.set(rf.left, rf.top - ((int) textHeight / 2), rf.right, rf.bottom - ((int) textHeight / 2));

            float textBottom = rf2.bottom;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                float textLeft = rf.centerX() - rect.width() / 2;
                textBottom = textBottom + (rect.height() + 3);
                c.drawText(stringArray[j], textLeft - rect.left, textBottom - rect.bottom, paint);
            }

            // Puts in the Icon
            Drawable drawable = getResources().getDrawable(menuEntries.get(i).getIcon());
            drawable.setBounds(rf2);
            if (f != enabled && Wedge2Shown == true) {
                drawable.setAlpha(disabledAlpha);
            } else {
                drawable.setAlpha(pictureAlpha);
            }
            drawable.draw(c);

            // Icon Only
        } else if (menuEntries.get(i).getIcon() != 0) {
            // Puts in the Icon
            Drawable drawable = getResources().getDrawable(menuEntries.get(i).getIcon());
            drawable.setBounds(rf);
            if (f != enabled && Wedge2Shown == true) {
                drawable.setAlpha(disabledAlpha);
            } else {
                drawable.setAlpha(pictureAlpha);
            }
            drawable.draw(c);

            // Text Only
        } else {
            // Puts in the Text if no Icon
            paint.setColor(textColor);
            if (f != enabled && Wedge2Shown == true) {
                paint.setAlpha(disabledAlpha);
            } else {
                paint.setAlpha(textAlpha);
            }
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(textSize + 10);

            // This will look for a "new line" and split into multiple lines
            String menuItemName = menuEntries.get(i).getLabel();
            String[] stringArray = menuItemName.split("\n");

            // gets total height
            Rect rect = new Rect();
            float textHeight = 0;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                textHeight = textHeight + (rect.height() + 3);
            }

            float textBottom = rf.centerY() - (textHeight / 2);
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                float textLeft = rf.centerX() - rect.width() / 2;
                textBottom = textBottom + (rect.height() + 3);
                c.drawText(stringArray[j], textLeft - rect.left, textBottom - rect.bottom, paint);
            }
        }

    }

    // Animate the outer ring in/out
    if (animateOuterIn == true) {
        animateOuterWedges(ANIMATE_IN);
    } else if (animateOuterOut == true) {
        animateOuterWedges(ANIMATE_OUT);
    }
    //outer
    if (Wedge2Shown == true) {

        for (int i = 0; i < Wedges2.length; i++) {
            RadialMenuWedge f = Wedges2[i];
            paint.setColor(outlineColor);
            paint.setAlpha(20);
            paint.setStyle(Paint.Style.STROKE);
            c.drawPath(f, paint);
            if (f == selected2) {
                paint.setColor(selectedColor);
                paint.setAlpha(selectedAlpha);
                paint.setStyle(Paint.Style.FILL);
                c.drawPath(f, paint);
            } else {
                paint.setColor(wedge2Color);
                paint.setAlpha(wedge2Alpha);
                paint.setStyle(Paint.Style.FILL);
                c.drawPath(f, paint);
            }

            Rect rf = iconRect2[i];
            if ((wedge2Data.getChildren().get(i).getIcon() != 0)
                    && (wedge2Data.getChildren().get(i).getLabel() != null)) {

                // This will look for a "new line" and split into multiple
                // lines
                String menuItemName = wedge2Data.getChildren().get(i).getLabel();
                String[] stringArray = menuItemName.split("\n");

                paint.setColor(textColor);
                paint.setAlpha(textAlpha);
                paint.setStyle(Paint.Style.FILL);
                paint.setTextSize(animateTextSize);

                Rect rect = new Rect();
                float textHeight = 0;
                for (int j = 0; j < stringArray.length; j++) {
                    paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                    textHeight = textHeight + (rect.height() + 3);
                }

                Rect rf2 = new Rect();
                rf2.set(rf.left, rf.top - ((int) textHeight / 2), rf.right, rf.bottom - ((int) textHeight / 2));

                float textBottom = rf2.bottom;
                for (int j = 0; j < stringArray.length; j++) {
                    paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                    float textLeft = rf.centerX() - rect.width() / 2;
                    textBottom = textBottom + (rect.height() + 3);
                    c.drawText(stringArray[j], textLeft - rect.left, textBottom - rect.bottom, paint);
                }

                // Puts in the Icon
                Drawable drawable = getResources().getDrawable(wedge2Data.getChildren().get(i).getIcon());
                drawable.setBounds(rf2);
                drawable.setAlpha(pictureAlpha);
                drawable.draw(c);

                // Icon Only
            } else if (wedge2Data.getChildren().get(i).getIcon() != 0) {
                // Puts in the Icon
                Drawable drawable = getResources().getDrawable(wedge2Data.getChildren().get(i).getIcon());
                drawable.setBounds(rf);
                drawable.setAlpha(pictureAlpha);
                drawable.draw(c);

                // Text Only
            } else {
                // Puts in the Text if no Icon
                paint.setColor(textColor);
                paint.setAlpha(textAlpha);
                paint.setStyle(Paint.Style.FILL);
                paint.setTextSize(animateTextSize);

                // This will look for a "new line" and split into multiple
                // lines
                String menuItemName = wedge2Data.getChildren().get(i).getLabel();
                String[] stringArray = menuItemName.split("\n");

                // gets total height
                Rect rect = new Rect();
                float textHeight = 0;
                for (int j = 0; j < stringArray.length; j++) {
                    paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                    textHeight = textHeight + (rect.height() + 3);
                }

                float textBottom = rf.centerY() - (textHeight / 2);
                for (int j = 0; j < stringArray.length; j++) {
                    paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                    float textLeft = rf.centerX() - rect.width() / 2;
                    textBottom = textBottom + (rect.height() + 3);
                    c.drawText(stringArray[j], textLeft - rect.left, textBottom - rect.bottom, paint);
                }
            }
        }
    }

    //Check if the user has given input for centre circle
    if (centerCircle != null) {
        // Draws the Middle Circle
        paint.setColor(outlineColor);
        paint.setAlpha(outlineAlpha);
        paint.setStyle(Paint.Style.STROKE);
        c.drawCircle(xPosition, yPosition, cRadius, paint);
        if (inCircle == true) {
            paint.setColor(selectedColor);
            paint.setAlpha(selectedAlpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawCircle(xPosition, yPosition, cRadius, paint);
            helper.onCloseAnimation(this, xPosition, yPosition, xSource, ySource);
        } else {
            paint.setColor(defaultColor);
            paint.setAlpha(defaultAlpha);
            paint.setStyle(Paint.Style.FILL);
            c.drawCircle(xPosition, yPosition, cRadius, paint);
        }

        // Draw the circle picture
        if ((centerCircle.getIcon() != 0) && (centerCircle.getLabel() != null)) {

            // This will look for a "new line" and split into multiple lines
            String menuItemName = centerCircle.getLabel();
            String[] stringArray = menuItemName.split("\n");

            paint.setColor(textColor);
            paint.setAlpha(textAlpha);
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(textSize);

            Rect rectText = new Rect();
            Rect rectIcon = new Rect();
            Drawable drawable = getResources().getDrawable(centerCircle.getIcon());

            int h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize, MaxIconSize);
            int w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize, MaxIconSize);
            rectIcon.set(xPosition - w / 2, yPosition - h / 2, xPosition + w / 2, yPosition + h / 2);

            float textHeight = 0;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rectText);
                textHeight = textHeight + (rectText.height() + 3);
            }

            rectIcon.set(rectIcon.left, rectIcon.top - ((int) textHeight / 2), rectIcon.right,
                    rectIcon.bottom - ((int) textHeight / 2));

            float textBottom = rectIcon.bottom;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rectText);
                float textLeft = xPosition - rectText.width() / 2;
                textBottom = textBottom + (rectText.height() + 3);
                c.drawText(stringArray[j], textLeft - rectText.left, textBottom - rectText.bottom, paint);
            }

            // Puts in the Icon
            drawable.setBounds(rectIcon);
            drawable.setAlpha(pictureAlpha);
            drawable.draw(c);

            // Icon Only
        } else if (centerCircle.getIcon() != 0) {

            Rect rect = new Rect();

            Drawable drawable = getResources().getDrawable(centerCircle.getIcon());

            int h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize, MaxIconSize);
            int w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize, MaxIconSize);
            rect.set(xPosition - w / 2, yPosition - h / 2, xPosition + w / 2, yPosition + h / 2);

            drawable.setBounds(rect);
            drawable.setAlpha(pictureAlpha);
            drawable.draw(c);

            // Text Only
        } else {
            // Puts in the Text if no Icon
            paint.setColor(textColor);
            paint.setAlpha(textAlpha);
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(textSize);

            // This will look for a "new line" and split into multiple lines
            String menuItemName = centerCircle.getLabel();
            String[] stringArray = menuItemName.split("\n");

            // gets total height
            Rect rect = new Rect();
            float textHeight = 0;
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                textHeight = textHeight + (rect.height() + 3);
            }

            float textBottom = yPosition - (textHeight / 2);
            for (int j = 0; j < stringArray.length; j++) {
                paint.getTextBounds(stringArray[j], 0, stringArray[j].length(), rect);
                float textLeft = xPosition - rect.width() / 2;
                textBottom = textBottom + (rect.height() + 3);
                c.drawText(stringArray[j], textLeft - rect.left, textBottom - rect.bottom, paint);
            }

        }
    }

    // Draws Text in TextBox
    if (headerString != null) {

        paint.setTextSize(headerTextSize);
        paint.getTextBounds(headerString, 0, headerString.length(), this.textRect);
        if (HeaderBoxBounded == false) {
            determineHeaderBox();
            HeaderBoxBounded = true;
        }

        paint.setColor(outlineColor);
        paint.setAlpha(outlineAlpha);
        paint.setStyle(Paint.Style.STROKE);
        c.drawRoundRect(this.textBoxRect, scalePX(5), scalePX(5), paint);
        paint.setColor(headerBackgroundColor);
        paint.setAlpha(headerBackgroundAlpha);
        paint.setStyle(Paint.Style.FILL);
        c.drawRoundRect(this.textBoxRect, scalePX(5), scalePX(5), paint);

        paint.setColor(headerTextColor);
        paint.setAlpha(headerTextAlpha);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(headerTextSize);
        c.drawText(headerString, headerTextLeft, headerTextBottom, paint);
    }

}

From source file:io.doist.datetimepicker.time.RadialTimePickerView.java

private void drawSelector(Canvas canvas, int index) {
    // Calculate the current radius at which to place the selection circle.
    mLineLength[index] = (int) (mCircleRadius[index] * mNumbersRadiusMultiplier[index]
            * mAnimationRadiusMultiplier[index]);

    double selectionRadians = Math.toRadians(mSelectionDegrees[index]);

    int pointX = mXCenter + (int) (mLineLength[index] * Math.sin(selectionRadians));
    int pointY = mYCenter - (int) (mLineLength[index] * Math.cos(selectionRadians));

    int color;//from   ww  w.j a  va2  s  .  c om
    int alpha;
    Paint paint;

    // Draw the selection circle
    color = mColorSelector[index % 2][SELECTOR_CIRCLE];
    alpha = mAlphaSelector[index % 2][SELECTOR_CIRCLE].getValue();
    paint = mPaintSelector[index % 2][SELECTOR_CIRCLE];
    paint.setColor(color);
    paint.setAlpha(getMultipliedAlpha(color, alpha));
    canvas.drawCircle(pointX, pointY, mSelectionRadius[index], paint);

    // Draw the dot if needed
    if (mSelectionDegrees[index] % 30 != 0) {
        // We're not on a direct tick
        color = mColorSelector[index % 2][SELECTOR_DOT];
        alpha = mAlphaSelector[index % 2][SELECTOR_DOT].getValue();
        paint = mPaintSelector[index % 2][SELECTOR_DOT];
        paint.setColor(color);
        paint.setAlpha(getMultipliedAlpha(color, alpha));
        canvas.drawCircle(pointX, pointY, (mSelectionRadius[index] * 2 / 7), paint);
    } else {
        // We're not drawing the dot, so shorten the line to only go as far as the edge of the
        // selection circle
        int lineLength = mLineLength[index] - mSelectionRadius[index];
        pointX = mXCenter + (int) (lineLength * Math.sin(selectionRadians));
        pointY = mYCenter - (int) (lineLength * Math.cos(selectionRadians));
    }

    // Draw the line
    color = mColorSelector[index % 2][SELECTOR_LINE];
    alpha = mAlphaSelector[index % 2][SELECTOR_LINE].getValue();
    paint = mPaintSelector[index % 2][SELECTOR_LINE];
    paint.setColor(color);
    paint.setAlpha(getMultipliedAlpha(color, alpha));
    canvas.drawLine(mXCenter, mYCenter, pointX, pointY, paint);
}

From source file:org.telegram.ui.SettingsActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_avatar_actionBarSelectorBlue), false);
    actionBar.setItemsColor(Theme.getColor(Theme.key_avatar_actionBarIconBlue), false);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAddToContainer(false);//  w  w w .java 2s.c  o  m
    extraHeight = 88;
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == edit_name) {
                presentFragment(new ChangeNameActivity());
            } else if (id == logout) {
                presentFragment(new LogoutActivity());
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
    item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName));
    item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut));

    int scrollTo;
    int scrollToPosition = 0;
    Object writeButtonTag = null;
    if (listView != null) {
        scrollTo = layoutManager.findFirstVisibleItemPosition();
        View topView = layoutManager.findViewByPosition(scrollTo);
        if (topView != null) {
            scrollToPosition = topView.getTop();
        } else {
            scrollTo = -1;
        }
        writeButtonTag = writeButton.getTag();
    } else {
        scrollTo = -1;
    }

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context) {
        @Override
        protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
            if (child == listView) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (parentLayout != null) {
                    int actionBarHeight = 0;
                    int childCount = getChildCount();
                    for (int a = 0; a < childCount; a++) {
                        View view = getChildAt(a);
                        if (view == child) {
                            continue;
                        }
                        if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
                            if (((ActionBar) view).getCastShadows()) {
                                actionBarHeight = view.getMeasuredHeight();
                            }
                            break;
                        }
                    }
                    parentLayout.drawHeaderShadow(canvas, actionBarHeight);
                }
                return result;
            } else {
                return super.drawChild(canvas, child, drawingTime);
            }
        }
    };
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    FrameLayout frameLayout = (FrameLayout) fragmentView;

    listView = new RecyclerListView(context);
    listView.setVerticalScrollBarEnabled(false);
    listView.setLayoutManager(
            layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {
                @Override
                public boolean supportsPredictiveItemAnimations() {
                    return false;
                }
            });
    listView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.TOP | Gravity.LEFT));
    listView.setAdapter(listAdapter);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setOnItemClickListener((view, position) -> {
        if (position == notificationRow) {
            presentFragment(new NotificationsSettingsActivity());
        } else if (position == privacyRow) {
            presentFragment(new PrivacySettingsActivity());
        } else if (position == dataRow) {
            presentFragment(new DataSettingsActivity());
        } else if (position == chatRow) {
            presentFragment(new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC));
        } else if (position == helpRow) {
            BottomSheet.Builder builder = new BottomSheet.Builder(context);
            builder.setApplyTopPadding(false);

            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);

            HeaderCell headerCell = new HeaderCell(context, true, 23, 15, false);
            headerCell.setHeight(47);
            headerCell.setText(LocaleController.getString("SettingsHelp", R.string.SettingsHelp));
            linearLayout.addView(headerCell);

            LinearLayout linearLayoutInviteContainer = new LinearLayout(context);
            linearLayoutInviteContainer.setOrientation(LinearLayout.VERTICAL);
            linearLayout.addView(linearLayoutInviteContainer,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            int count = 6;
            for (int a = 0; a < count; a++) {
                if (a >= 3 && a <= 4 && !BuildVars.LOGS_ENABLED || a == 5 && !BuildVars.DEBUG_VERSION) {
                    continue;
                }
                TextCell textCell = new TextCell(context);
                String text;
                switch (a) {
                case 0:
                    text = LocaleController.getString("AskAQuestion", R.string.AskAQuestion);
                    break;
                case 1:
                    text = LocaleController.getString("TelegramFAQ", R.string.TelegramFAQ);
                    break;
                case 2:
                    text = LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy);
                    break;
                case 3:
                    text = LocaleController.getString("DebugSendLogs", R.string.DebugSendLogs);
                    break;
                case 4:
                    text = LocaleController.getString("DebugClearLogs", R.string.DebugClearLogs);
                    break;
                case 5:
                default:
                    text = "Switch Backend";
                    break;
                }
                textCell.setText(text,
                        BuildVars.LOGS_ENABLED || BuildVars.DEBUG_VERSION ? a != count - 1 : a != 2);
                textCell.setTag(a);
                textCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                linearLayoutInviteContainer.addView(textCell,
                        LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                textCell.setOnClickListener(v2 -> {
                    Integer tag = (Integer) v2.getTag();
                    switch (tag) {
                    case 0: {
                        showDialog(AlertsCreator.createSupportAlert(SettingsActivity.this));
                        break;
                    }
                    case 1:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
                        break;
                    case 2:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
                        break;
                    case 3:
                        sendLogs();
                        break;
                    case 4:
                        FileLog.cleanupLogs();
                        break;
                    case 5: {
                        if (getParentActivity() == null) {
                            return;
                        }
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
                        builder1.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
                        builder1.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder1.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                (dialogInterface, i) -> {
                                    SharedConfig.pushAuthKey = null;
                                    SharedConfig.pushAuthKeyId = null;
                                    SharedConfig.saveConfig();
                                    ConnectionsManager.getInstance(currentAccount).switchBackend();
                                });
                        builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder1.create());
                        break;
                    }
                    }
                    builder.getDismissRunnable().run();
                });
            }
            builder.setCustomView(linearLayout);
            showDialog(builder.create());
        } else if (position == languageRow) {
            presentFragment(new LanguageSelectActivity());
        } else if (position == usernameRow) {
            presentFragment(new ChangeUsernameActivity());
        } else if (position == bioRow) {
            if (userInfo != null) {
                presentFragment(new ChangeBioActivity());
            }
        } else if (position == numberRow) {
            presentFragment(new ChangePhoneHelpActivity());
        }
    });

    listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {

        private int pressCount = 0;

        @Override
        public boolean onItemClick(View view, int position) {
            if (position == versionRow) {
                pressCount++;
                if (pressCount >= 2 || BuildVars.DEBUG_PRIVATE_VERSION) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu));
                    CharSequence[] items;
                    items = new CharSequence[] {
                            LocaleController.getString("DebugMenuImportContacts",
                                    R.string.DebugMenuImportContacts),
                            LocaleController.getString("DebugMenuReloadContacts",
                                    R.string.DebugMenuReloadContacts),
                            LocaleController.getString("DebugMenuResetContacts",
                                    R.string.DebugMenuResetContacts),
                            LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs),
                            BuildVars.LOGS_ENABLED
                                    ? LocaleController.getString("DebugMenuDisableLogs",
                                            R.string.DebugMenuDisableLogs)
                                    : LocaleController.getString("DebugMenuEnableLogs",
                                            R.string.DebugMenuEnableLogs),
                            SharedConfig.inappCamera
                                    ? LocaleController.getString("DebugMenuDisableCamera",
                                            R.string.DebugMenuDisableCamera)
                                    : LocaleController.getString("DebugMenuEnableCamera",
                                            R.string.DebugMenuEnableCamera),
                            LocaleController.getString("DebugMenuClearMediaCache",
                                    R.string.DebugMenuClearMediaCache),
                            LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings),
                            null, BuildVars.DEBUG_PRIVATE_VERSION ? "Check for app updates" : null };
                    builder.setItems(items, (dialog, which) -> {
                        if (which == 0) {
                            UserConfig.getInstance(currentAccount).syncContacts = true;
                            UserConfig.getInstance(currentAccount).saveConfig(false);
                            ContactsController.getInstance(currentAccount).forceImportContacts();
                        } else if (which == 1) {
                            ContactsController.getInstance(currentAccount).loadContacts(false, 0);
                        } else if (which == 2) {
                            ContactsController.getInstance(currentAccount).resetImportedContacts();
                        } else if (which == 3) {
                            MessagesController.getInstance(currentAccount).forceResetDialogs();
                        } else if (which == 4) {
                            BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED;
                            SharedPreferences sharedPreferences = ApplicationLoader.applicationContext
                                    .getSharedPreferences("systemConfig", Context.MODE_PRIVATE);
                            sharedPreferences.edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit();
                        } else if (which == 5) {
                            SharedConfig.toggleInappCamera();
                        } else if (which == 6) {
                            MessagesStorage.getInstance(currentAccount).clearSentMedia();
                            SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit();
                            SharedConfig.setNoSoundHintShowed(false);
                        } else if (which == 7) {
                            VoIPHelper.showCallDebugSettings(getParentActivity());
                        } else if (which == 8) {
                            SharedConfig.toggleRoundCamera16to9();
                        } else if (which == 9) {
                            ((LaunchActivity) getParentActivity()).checkAppUpdate(true);
                        }
                    });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    try {
                        Toast.makeText(getParentActivity(), "\\_()_/", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            }
            return false;
        }
    });

    frameLayout.addView(actionBar);

    extraHeightView = new View(context);
    extraHeightView.setPivotY(0);
    extraHeightView.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88));

    shadowView = new View(context);
    shadowView.setBackgroundResource(R.drawable.header_shadow);
    frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));

    avatarContainer = new FrameLayout(context);
    avatarContainer.setPivotX(LocaleController.isRTL ? AndroidUtilities.dp(42) : 0);
    avatarContainer.setPivotY(0);
    frameLayout.addView(avatarContainer,
            LayoutHelper.createFrame(42, 42,
                    Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                    (LocaleController.isRTL ? 0 : 64), 0, (LocaleController.isRTL ? 64 : 0), 0));
    avatarContainer.setOnClickListener(v -> {
        if (avatar != null) {
            return;
        }
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user != null && user.photo != null && user.photo.photo_big != null) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(user.photo.photo_big, provider);
        }
    });

    avatarImage = new BackupImageView(context);
    avatarImage.setRoundRadius(AndroidUtilities.dp(21));
    avatarContainer.addView(avatarImage, LayoutHelper.createFrame(42, 42));

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0x55000000);

    avatarProgressView = new RadialProgressView(context) {
        @Override
        protected void onDraw(Canvas canvas) {
            if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
                paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
                canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, AndroidUtilities.dp(21),
                        paint);
            }
            super.onDraw(canvas);
        }
    };
    avatarProgressView.setSize(AndroidUtilities.dp(26));
    avatarProgressView.setProgressColor(0xffffffff);
    avatarContainer.addView(avatarProgressView, LayoutHelper.createFrame(42, 42));

    showAvatarProgress(false, false);

    nameTextView = new TextView(context) {
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setPivotX(LocaleController.isRTL ? getMeasuredWidth() : 0);
        }
    };
    nameTextView.setTextColor(Theme.getColor(Theme.key_profile_title));
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    nameTextView.setLines(1);
    nameTextView.setMaxLines(1);
    nameTextView.setSingleLine(true);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setPivotY(0);
    frameLayout.addView(nameTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    onlineTextView = new TextView(context);
    onlineTextView.setTextColor(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue));
    onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    onlineTextView.setLines(1);
    onlineTextView.setMaxLines(1);
    onlineTextView.setSingleLine(true);
    onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
    onlineTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    frameLayout.addView(onlineTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    writeButton = new ImageView(context);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56),
            Theme.getColor(Theme.key_profile_actionBackground),
            Theme.getColor(Theme.key_profile_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile)
                .mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    writeButton.setBackgroundDrawable(drawable);
    writeButton.setImageResource(R.drawable.menu_camera_av);
    writeButton.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_profile_actionIcon), PorterDuff.Mode.MULTIPLY));
    writeButton.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed },
                ObjectAnimator
                        .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4))
                        .setDuration(200));
        animator.addState(new int[] {},
                ObjectAnimator
                        .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2))
                        .setDuration(200));
        writeButton.setStateListAnimator(animator);
        writeButton.setOutlineProvider(new ViewOutlineProvider() {
            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    frameLayout.addView(writeButton,
            LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP,
                    LocaleController.isRTL ? 16 : 0, 0, LocaleController.isRTL ? 0 : 16, 0));
    writeButton.setOnClickListener(v -> {
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user == null) {
            user = UserConfig.getInstance(currentAccount).getCurrentUser();
        }
        if (user == null) {
            return;
        }
        imageUpdater.openMenu(
                user.photo != null && user.photo.photo_big != null
                        && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty),
                () -> MessagesController.getInstance(currentAccount).deleteUserPhoto(null));
    });

    if (scrollTo != -1) {
        layoutManager.scrollToPositionWithOffset(scrollTo, scrollToPosition);

        if (writeButtonTag != null) {
            writeButton.setTag(0);
            writeButton.setScaleX(0.2f);
            writeButton.setScaleY(0.2f);
            writeButton.setAlpha(0.0f);
            writeButton.setVisibility(View.GONE);
        }
    }

    needLayout();

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (layoutManager.getItemCount() == 0) {
                return;
            }
            int height = 0;
            View child = recyclerView.getChildAt(0);
            if (child != null) {
                if (layoutManager.findFirstVisibleItemPosition() == 0) {
                    height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0);
                }
                if (extraHeight != height) {
                    extraHeight = height;
                    needLayout();
                }
            }
        }
    });

    return fragmentView;
}

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

private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
    Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
    final Canvas c = mCachedShortcutPreviewCanvas.get();
    if (tempBitmap == null || tempBitmap.getWidth() != maxWidth || tempBitmap.getHeight() != maxHeight) {
        tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
        mCachedShortcutPreviewBitmap.set(tempBitmap);
    } else {//from   w  w w  .jav a 2  s  .  c  o m
        c.setBitmap(tempBitmap);
        c.drawColor(0, PorterDuff.Mode.CLEAR);
        c.setBitmap(null);
    }
    // Render the icon
    Drawable icon = mIconCache.getFullResIcon(info);

    int paddingTop = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
    int paddingLeft = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
    int paddingRight = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);

    int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);

    renderDrawableToBitmap(icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);

    Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
    c.setBitmap(preview);
    Paint p = mCachedShortcutPreviewPaint.get();
    if (p == null) {
        p = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
        p.setAlpha((int) (255 * 0.06f));
        //float density = 1f;
        //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
        mCachedShortcutPreviewPaint.set(p);
    }
    c.drawBitmap(tempBitmap, 0, 0, p);
    c.setBitmap(null);

    renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);

    return preview;
}

From source file:com.appeaser.sublimepickerlibrary.timepicker.RadialTimePickerView.java

/**
 * Draw the 12 text values at the positions specified by the textGrid parameters.
 *///  w w w . j  ava 2 s.com
private void drawTextElements(Canvas canvas, float textSize, Typeface typeface, ColorStateList textColor,
        String[] texts, float[] textX, float[] textY, Paint paint, int alpha, boolean showActivated,
        int activatedDegrees, boolean activatedOnly) {
    paint.setTextSize(textSize);
    paint.setTypeface(typeface);

    // The activated index can touch a range of elements.
    final float activatedIndex = activatedDegrees / (360.0f / NUM_POSITIONS);
    final int activatedFloor = (int) activatedIndex;
    final int activatedCeil = ((int) Math.ceil(activatedIndex)) % NUM_POSITIONS;

    for (int i = 0; i < 12; i++) {
        final boolean activated = (activatedFloor == i || activatedCeil == i);
        if (activatedOnly && !activated) {
            continue;
        }

        final int stateMask = SUtils.STATE_ENABLED | (showActivated && activated ? SUtils.STATE_ACTIVATED : 0);
        final int color = textColor.getColorForState(SUtils.resolveStateSet(stateMask), 0);
        paint.setColor(color);
        paint.setAlpha(getMultipliedAlpha(color, alpha));

        canvas.drawText(texts[i], textX[i], textY[i], paint);
    }
}

From source file:com.almalence.opencam.SavingService.java

protected void drawTextWithBackground(Canvas canvas, Paint paint, String text, int foreground, int background,
        int imageWidth, int imageHeight) {
    Rect text_bounds = new Rect();
    paint.setColor(foreground);/*from w ww .j  av a2s  .  c o  m*/
    String[] resText = text.split("\n");
    String maxLengthText = "";

    if (resText.length > 1) {
        maxLengthText = resText[0].length() > resText[1].length() ? resText[0] : resText[1];
    } else if (resText.length > 0) {
        maxLengthText = resText[0];
    }

    final float scale = getResources().getDisplayMetrics().density;
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(background);
    paint.setAlpha(64);
    paint.getTextBounds(text, 0, maxLengthText.length(), text_bounds);
    final int padding = (int) (2 * scale + 0.5f); // convert dps to pixels

    int textWidth = 0;
    int textHeight = text_bounds.bottom - text_bounds.top;
    if (paint.getTextAlign() == Paint.Align.RIGHT || paint.getTextAlign() == Paint.Align.CENTER) {
        float width = paint.measureText(maxLengthText); // n.b., need to use
        // measureText
        // rather than
        // getTextBounds
        // here
        textWidth = (int) width;
    }

    text_bounds.left = imageWidth - textWidth - resText.length * padding;
    text_bounds.right = imageWidth - padding;
    if (resText.length > 1) {
        text_bounds.top = imageHeight - resText.length * padding - resText.length * textHeight - textHeight;
    } else {
        text_bounds.top = imageHeight - 2 * padding - textHeight;
        textHeight /= 3;
    }
    text_bounds.bottom = imageHeight - padding;

    paint.setColor(foreground);
    if (resText.length > 0) {
        canvas.drawText(resText[0], imageWidth - 5 * padding,
                imageHeight - resText.length * textHeight - textHeight / 2, paint);
    }
    if (resText.length > 1) {
        canvas.drawText(resText[1], imageWidth - 5 * padding, imageHeight - (resText.length - 1) * textHeight,
                paint);
    }
    if (resText.length > 2) {
        canvas.drawText(resText[2], imageWidth - 5 * padding,
                imageHeight - (resText.length - 2) * textHeight + textHeight / 2, paint);
    }
    if (resText.length > 3) {
        canvas.drawText(resText[3], imageWidth - 5 * padding, imageHeight - textHeight / 4, paint);
    }
}

From source file:com.tr4android.support.extension.picker.time.RadialTimePickerView.java

/**
 * Draw the 12 text values at the positions specified by the textGrid parameters.
 *///from   www . j  ava2 s.  c o  m
private void drawTextElements(Canvas canvas, float textSize, Typeface typeface, ColorStateList textColor,
        String[] texts, float[] textX, float[] textY, Paint paint, int alpha, boolean showActivated,
        int activatedDegrees, boolean activatedOnly) {
    paint.setTextSize(textSize);
    paint.setTypeface(typeface);

    // The activated index can touch a range of elements.
    final float activatedIndex = activatedDegrees / (360.0f / NUM_POSITIONS);
    final int activatedFloor = (int) activatedIndex;
    final int activatedCeil = ((int) Math.ceil(activatedIndex)) % NUM_POSITIONS;

    for (int i = 0; i < 12; i++) {
        final boolean activated = (activatedFloor == i || activatedCeil == i);
        if (activatedOnly && !activated) {
            continue;
        }

        final int[] stateMask = new int[] { android.R.attr.state_enabled,
                (showActivated && activated ? android.R.attr.state_selected : 0) };
        final int color = textColor.getColorForState(stateMask, 0);
        paint.setColor(color);
        paint.setAlpha(getMultipliedAlpha(color, alpha));

        canvas.drawText(texts[i], textX[i], textY[i], paint);
    }
}