Example usage for android.text TextPaint setColor

List of usage examples for android.text TextPaint setColor

Introduction

In this page you can find the example usage for android.text TextPaint setColor.

Prototype

public void setColor(@ColorInt int color) 

Source Link

Document

Set the paint's color.

Usage

From source file:com.android.contacts.ShortcutIntentBuilder.java

/**
 * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
 * number, and if there is a photo also adds the call action icon.
 *///ww w . ja va 2s  .com
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    final Drawable phoneDrawable = r.getDrawableForDensity(actionResId, mIconDensity);
    // These icons have the same height and width so either is fine for the size.
    final Bitmap phoneIcon = BitmapUtil.drawableToBitmap(phoneDrawable, phoneDrawable.getIntrinsicHeight());

    Bitmap icon = generateQuickContactIcon(photo);
    Canvas canvas = new Canvas(icon);

    // Copy in the photo
    Paint photoPaint = new Paint();
    photoPaint.setDither(true);
    photoPaint.setFilterBitmap(true);
    Rect dst = new Rect(0, 0, mIconSize, mIconSize);

    // Create an overlay for the phone number type if we're pre-O. O created shortcuts have the
    // app badge which overlaps the type overlay.
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);
    if (!BuildCompat.isAtLeastO() && overlay != null) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(r.getDimension(R.dimen.shortcut_overlay_text_size));
        textPaint.setColor(r.getColor(R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f, r.getColor(R.color.textColorIconOverlayShadow));

        final FontMetricsInt fmi = textPaint.getFontMetricsInt();

        // First fill in a darker background around the text to be drawn
        final Paint workPaint = new Paint();
        workPaint.setColor(mOverlayTextBackgroundColor);
        workPaint.setStyle(Paint.Style.FILL);
        final int textPadding = r.getDimensionPixelOffset(R.dimen.shortcut_overlay_text_background_padding);
        final int textBandHeight = (fmi.descent - fmi.ascent) + textPadding * 2;
        dst.set(0, mIconSize - textBandHeight, mIconSize, mIconSize);
        canvas.drawRect(dst, workPaint);

        overlay = TextUtils.ellipsize(overlay, textPaint, mIconSize, TruncateAt.END);
        final float textWidth = textPaint.measureText(overlay, 0, overlay.length());
        canvas.drawText(overlay, 0, overlay.length(), (mIconSize - textWidth) / 2,
                mIconSize - fmi.descent - textPadding, textPaint);
    }

    // Draw the phone action icon as an overlay
    int iconWidth = icon.getWidth();
    if (BuildCompat.isAtLeastO()) {
        // On O we need to calculate where the phone icon goes slightly differently. The whole
        // canvas area is 108dp, a centered circle with a diameter of 66dp is the "safe zone".
        // So we start the drawing the phone icon at
        // 108dp - 21 dp (distance from right edge of safe zone to the edge of the canvas)
        // - 24 dp (size of the phone icon) on the x axis (left)
        // The y axis is simply 21dp for the distance to the safe zone (top).
        // See go/o-icons-eng for more details and a handy picture.
        final int left = (int) (mIconSize - (45 * density));
        final int top = (int) (21 * density);
        canvas.drawBitmap(phoneIcon, left, top, photoPaint);
    } else {
        dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
        canvas.drawBitmap(phoneIcon, null, dst, photoPaint);
    }

    canvas.setBitmap(null);
    return icon;
}

From source file:com.semfapp.adamdilger.semf.Take5PdfDocument.java

public float drawRiskElement(int height, Take5RiskElement element) {
    final float singleLineHeight = 12.5f;
    float totalItemHeight;

    TextPaint textPaint = new TextPaint();
    textPaint.setTypeface(roboto);/*w w w. ja  v  a 2  s  .c o m*/
    textPaint.setTextSize(FONT11);
    textPaint.setColor(Color.BLACK);

    String oneString = "";
    String twoString = "";

    if (element.getOne() != null) {
        oneString = element.getOne();
    }
    if (element.getTwo() != null) {
        twoString = element.getTwo();
    }

    StaticLayout one = new StaticLayout(oneString, textPaint, 235, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
            false);
    StaticLayout rating = new StaticLayout(element.getRating().toString(), textPaint, 100,
            Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    StaticLayout two = new StaticLayout(twoString, textPaint, 250, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
            false);

    if (one.getLineCount() > two.getLineCount()) {
        totalItemHeight = singleLineHeight * one.getLineCount();
    } else {
        totalItemHeight = singleLineHeight * two.getLineCount();
    }

    can.save();
    can.translate(15, height);
    one.draw(can);
    can.restore();

    can.save();
    can.translate(320, height);
    two.draw(can);
    can.restore();

    can.save();
    can.translate(270, height);
    rating.draw(can);
    can.restore();

    return totalItemHeight;
}

From source file:io.plaidapp.core.ui.transitions.ReflowText.java

private Layout createLayout(ReflowData data, Context context, boolean enforceMaxLines) {
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(data.textSize);//ww w.  ja  va2 s .co m
    paint.setColor(data.textColor);
    paint.setLetterSpacing(data.letterSpacing);
    if (data.fontResId != 0) {
        try {
            Typeface font = ResourcesCompat.getFont(context, data.fontResId);
            if (font != null) {
                paint.setTypeface(font);
            }
        } catch (Resources.NotFoundException nfe) {
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        StaticLayout.Builder builder = StaticLayout.Builder
                .obtain(data.text, 0, data.text.length(), paint, data.textWidth)
                .setLineSpacing(data.lineSpacingAdd, data.lineSpacingMult).setBreakStrategy(data.breakStrategy);
        if (enforceMaxLines && data.maxLines != -1) {
            builder.setMaxLines(data.maxLines);
            builder.setEllipsize(TextUtils.TruncateAt.END);
        }
        return builder.build();
    } else {
        return new StaticLayout(data.text, paint, data.textWidth, Layout.Alignment.ALIGN_NORMAL,
                data.lineSpacingMult, data.lineSpacingAdd, true);
    }
}

From source file:com.mjhram.geodata.GpsMainActivity.java

public Bitmap drawMultilineTextToBitmap(Context gContext, Bitmap bitmap, String gText) {
    // prepare canvas
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    //Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }/*from   w w w  . ja  v a 2 s . co  m*/
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);

    Canvas canvas = new Canvas(bitmap);

    // new antialiased Paint
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(61, 61, 61));
    // text size in pixels
    paint.setTextSize((int) (20 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
    //canvas.drawText("This is", 100, 100, paint);
    //canvas.drawText("multi-line", 100, 150, paint);
    //canvas.drawText("text", 100, 200, paint);

    // set text width to canvas width minus 16dp padding
    int textWidth = canvas.getWidth() - (int) (16 * scale);

    // init StaticLayout for text
    StaticLayout textLayout = new StaticLayout(gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f,
            0.0f, false);

    // get height of multiline text
    int textHeight = textLayout.getHeight();

    // get position of text's top left corner
    float x = (bitmap.getWidth() - textWidth) / 2;
    float y = bitmap.getHeight() - textHeight;

    // draw text to the Canvas center
    canvas.save();
    canvas.translate(x, y);
    textLayout.draw(canvas);
    canvas.restore();

    return bitmap;
}

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

private MoreImageSpan createMoreSpan(final int count) {
    final String moreText = String.format(mMoreItem.getText().toString(), count);
    final TextPaint morePaint = new TextPaint(getPaint());
    morePaint.setTextSize(mMoreItem.getTextSize());
    morePaint.setColor(mMoreItem.getCurrentTextColor());
    final int width = (int) morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
            + mMoreItem.getPaddingRight();
    final int height = getLineHeight();
    final Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(drawable);
    int adjustedHeight = height;
    final Layout layout = getLayout();
    if (layout != null)
        adjustedHeight -= layout.getLineDescent(0);
    canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
    final Drawable result = new BitmapDrawable(getResources(), drawable);
    result.setBounds(0, 0, width, height);
    return new MoreImageSpan(result);
}

From source file:com.tr4android.support.extension.picker.date.SimpleMonthView.java

/**
 * Draws the month days.//  w w  w. j a v a 2  s .  c  om
 */
private void drawDays(Canvas canvas) {
    final TextPaint p = mDayPaint;
    final int headerHeight = mMonthHeight + mDayOfWeekHeight;
    final int rowHeight = mDayHeight;
    final int colWidth = mCellWidth;

    // Text is vertically centered within the row height.
    final float halfLineHeight = (p.ascent() + p.descent()) / 2f;
    int rowCenter = headerHeight + rowHeight / 2;

    for (int day = 1, col = findDayOffset(); day <= mDaysInMonth; day++) {
        final int colCenter = colWidth * col + colWidth / 2;
        final int colCenterRtl;
        if (ViewCompatUtils.isLayoutRtl(this)) {
            colCenterRtl = mPaddedWidth - colCenter;
        } else {
            colCenterRtl = colCenter;
        }

        int state = 0;

        final boolean isDayEnabled = isDayEnabled(day);
        final boolean isDayActivated = mActivatedDay == day;
        if (isDayActivated) {
            state = VIEW_STATE_SELECTED;

            // Adjust the circle to be centered on the row.
            canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDaySelectorPaint);
        } else if (mTouchedItem == day) {
            state = VIEW_STATE_PRESSED;

            if (isDayEnabled) {
                // Adjust the circle to be centered on the row.
                canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDayHighlightPaint);
            }
        }

        final boolean isDayToday = mToday == day;
        final int dayTextColor;
        if (isDayToday && !isDayActivated) {
            dayTextColor = mDaySelectorPaint.getColor();
        } else {
            final int[] stateSet = buildState(isDayEnabled, state);
            dayTextColor = mDayTextColor.getColorForState(stateSet, 0);
        }
        p.setColor(dayTextColor);

        canvas.drawText(mDayFormatter.format(day), colCenterRtl, rowCenter - halfLineHeight, p);

        col++;

        if (col == DAYS_IN_WEEK) {
            col = 0;
            rowCenter += rowHeight;
        }
    }
}

From source file:connect.app.com.connect.calendar.SimpleMonthView.java

/**
 * Draws the month days.//from   w  w  w.jav a 2 s.c  o  m
 */
private void drawDays(Canvas canvas) {
    final TextPaint p = mDayPaint;
    final int headerHeight = mMonthHeight + mDayOfWeekHeight;
    final int rowHeight = mDayHeight;
    final int colWidth = mCellWidth;

    // Text is vertically centered within the row height.
    final float halfLineHeight = (p.ascent() + p.descent()) / 2f;
    int rowCenter = headerHeight + rowHeight / 2;

    for (int day = 1, col = findDayOffset(); day <= mDaysInMonth; day++) {
        final int colCenter = colWidth * col + colWidth / 2;
        final int colCenterRtl = colCenter;
        //            if (isLayoutRtl()) {
        //                colCenterRtl = mPaddedWidth - colCenter;
        //            } else {
        //                colCenterRtl = colCenter;
        //            }

        int stateMask = 0;

        final boolean isDayEnabled = isDayEnabled(day);
        //            if (isDayEnabled) {
        //                stateMask |= StateSet.VIEW_STATE_ENABLED;
        //            }

        final boolean isDayActivated = mActivatedDay == day;
        if (isDayActivated) {
            //                stateMask |= StateSet.VIEW_STATE_ACTIVATED;

            // Adjust the circle to be centered on the row.
            canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDaySelectorPaint);
        } else if (mTouchedItem == day) {
            //                stateMask |= StateSet.VIEW_STATE_PRESSED;

            if (isDayEnabled) {
                // Adjust the circle to be centered on the row.
                canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDayHighlightPaint);
            }
        }

        final boolean isDayToday = mToday == day;
        int dayTextColor = 0;
        if (isDayToday && !isDayActivated) {
            dayTextColor = mDaySelectorPaint.getColor();
        } else {
            //                final int[] stateSet = StateSet.get(stateMask);
            //                dayTextColor = mDayTextColor.getColorForState(stateSet, 0);
        }
        p.setColor(dayTextColor);

        canvas.drawText(mDayFormatter.format(day), colCenterRtl, rowCenter - halfLineHeight, p);

        col++;

        if (col == DAYS_IN_WEEK) {
            col = 0;
            rowCenter += rowHeight;
        }
    }
}

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

private DrawableRecipientChip constructChipSpan(final RecipientEntry contact, final boolean pressed,
        final boolean leaveIconSpace) throws NullPointerException {
    if (mChipBackground == null)
        throw new NullPointerException("Unable to render any chips as setChipDimensions was not called.");
    final TextPaint paint = getPaint();
    final float defaultSize = paint.getTextSize();
    final int defaultColor = paint.getColor();
    Bitmap tmpBitmap;/*w w  w.  ja v  a2s  . c  om*/
    if (pressed)
        tmpBitmap = createSelectedChip(contact, paint);
    else
        tmpBitmap = createUnselectedChip(contact, paint, leaveIconSpace);
    // Pass the full text, un-ellipsized, to the chip.
    final Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
    result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
    final DrawableRecipientChip recipientChip = new VisibleRecipientChip(result, contact);
    // Return text to the original size.
    paint.setTextSize(defaultSize);
    paint.setColor(defaultColor);
    return recipientChip;
}

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

private Bitmap createSelectedChip(final RecipientEntry contact, final TextPaint paint) {
    // Ellipsize the text so that it takes AT MOST the entire width of the
    // autocomplete text entry area. Make sure to leave space for padding
    // on the sides.
    final int height = (int) mChipHeight;
    final int deleteWidth = height;
    final float[] widths = new float[1];
    paint.getTextWidths(" ", widths);
    final String createChipDisplayText = createChipDisplayText(contact);
    final float calculateAvailableWidth = calculateAvailableWidth();
    final CharSequence ellipsizedText = ellipsizeText(createChipDisplayText, paint,
            calculateAvailableWidth - deleteWidth - widths[0]);
    // Make sure there is a minimum chip width so the user can ALWAYS
    // tap a chip without difficulty.
    final int width = Math.max(deleteWidth * 2,
            (int) Math.floor(paint.measureText(ellipsizedText, 0, ellipsizedText.length())) + mChipPadding * 2
                    + deleteWidth);/*w ww  .  ja  va2 s  .  c  om*/
    // Create the background of the chip.
    final Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(tmpBitmap);
    if (mChipBackgroundPressed != null) {
        mChipBackgroundPressed.setBounds(0, 0, width, height);
        mChipBackgroundPressed.draw(canvas);
        paint.setColor(sSelectedTextColor);
        // Vertically center the text in the chip.
        canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
                getTextYOffset((String) ellipsizedText, paint, height), paint);
        // Make the delete a square.
        final Rect backgroundPadding = new Rect();
        mChipBackgroundPressed.getPadding(backgroundPadding);
        mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 0 + backgroundPadding.top,
                width - backgroundPadding.right, height - backgroundPadding.bottom);
        mChipDelete.draw(canvas);
    } else
        Log.w(TAG, "Unable to draw a background for the chips as it was never set");
    return tmpBitmap;
}

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

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