Example usage for android.text TextPaint TextPaint

List of usage examples for android.text TextPaint TextPaint

Introduction

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

Prototype

public TextPaint(Paint p) 

Source Link

Usage

From source file:com.silentcircle.contacts.list.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.
 *//*from w w  w.  j  a va  2s .c o m*/
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    Bitmap phoneIcon = ((BitmapDrawable) r.getDrawableForDensity(actionResId, mIconDensity)).getBitmap();

    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
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);

    if (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(ContextCompat.getColor(mContext, R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f,
                ContextCompat.getColor(mContext, 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
    Rect src = new Rect(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight());
    int iconWidth = icon.getWidth();
    dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
    canvas.drawBitmap(phoneIcon, src, dst, photoPaint);

    canvas.setBitmap(null);

    return icon;
}

From source file:com.android.contacts.common.list.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.
 *///  w ww.  j av a 2 s.c om
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    Bitmap phoneIcon = ((BitmapDrawable) r.getDrawableForDensity(actionResId, mIconDensity)).getBitmap();

    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
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);

    if (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
    Rect src = new Rect(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight());
    int iconWidth = icon.getWidth();
    dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
    canvas.drawBitmap(phoneIcon, src, dst, photoPaint);

    canvas.setBitmap(null);

    return icon;
}

From source file:org.ciasaboark.tacere.manager.NotificationManagerWrapper.java

private Bitmap createMarkerIcon(Drawable backgroundImage, String text, int width, int height) {

    Bitmap canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    // Create a canvas, that will draw on to canvasBitmap.
    Canvas imageCanvas = new Canvas(canvasBitmap);

    // Draw the image to our canvas
    backgroundImage.draw(imageCanvas);/*from w w  w  . ja  v a2 s  .c o  m*/

    // Set up the paint for use with our Canvas
    TextPaint textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG | TextPaint.LINEAR_TEXT_FLAG);
    textPaint.setTextAlign(TextPaint.Align.CENTER);
    textPaint.setTypeface(Typeface.DEFAULT);
    textPaint.setTextSize(100f);
    textPaint.setColor(context.getResources().getColor(android.R.color.white));

    int xPos = (imageCanvas.getWidth() / 2);
    int yPos = (int) ((imageCanvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2));
    Rect r = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), r);
    //        yPos += (Math.abs(r.height()))/2;

    // Draw the text on top of our image
    imageCanvas.drawText(text, xPos, yPos, textPaint);

    // Combine background and text to a LayerDrawable
    LayerDrawable layerDrawable = new LayerDrawable(
            new Drawable[] { backgroundImage, new BitmapDrawable(canvasBitmap) });
    Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    layerDrawable.setBounds(0, 0, width, height);
    layerDrawable.draw(new Canvas(newBitmap));
    return newBitmap;
}

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 .java2 s.  c  o m
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: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);//  w w  w  .  j a v  a2s .  c o  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.example.view.wheel.WheelView.java

/**
 * Initializes resources/*from   w  w w.j  a v a 2  s.c  o m*/
 */
private void initResourcesIfNecessary() {
    if (itemsPaint == null) {
        itemsPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);
        //itemsPaint.density = getResources().getDisplayMetrics().density;
        itemsPaint.setTextSize(BaseUtil.dp2px(context, TEXT_SIZE));
    }

    if (valuePaint == null) {
        valuePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.FAKE_BOLD_TEXT_FLAG | Paint.DITHER_FLAG);
        //valuePaint.density = getResources().getDisplayMetrics().density;
        valuePaint.setTextSize(BaseUtil.dp2px(context, TEXT_SIZE));
        valuePaint.setColor(Color.BLUE);
        //   valuePaint.setShadowLayer(0.1f, 0, 0.1f, 0xFFC0C0C0);
    }
    if (linePaint == null) {
        linePaint = new Paint();
        linePaint.setColor(Color.parseColor("#FF6D4B"));
        linePaint.setStrokeWidth(10.0F);
    }
    if (centerDrawable == null) {
        centerDrawable = ContextCompat.getDrawable(context, R.drawable.wheel_val);
    }

    if (topShadow == null) {
        topShadow = new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS);
    }

    if (bottomShadow == null) {
        bottomShadow = new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS);
    }

    //setBackgroundResource(R.drawable.wheel_bg);
    setBackgroundColor(Color.WHITE);
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Move the reference of current layout to the {@link AtomicReference} for further use,
 * then clear current layout./*ww w.  j a  v a 2 s .c  o  m*/
 */
private void swap() {
    if (layout != null) {
        atomicReference.set(layout);
        layout = null;
        mTextPaint = new TextPaint(mTextPaint);
    }
    hasBeenMeasured = false;
}

From source file:com.ruesga.timelinechart.TimelineChartView.java

private void init(Context ctx, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    mUiHandler = new Handler(Looper.getMainLooper(), mMessenger);
    if (!isInEditMode()) {
        mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    }/*from   w  w  w . j av  a 2  s .c  o  m*/

    final Resources res = getResources();
    final Resources.Theme theme = ctx.getTheme();

    mTickFormats = getResources().getStringArray(R.array.tlcDefTickLabelFormats);
    mTickLabels = getResources().getStringArray(R.array.tlcDefTickLabelValues);

    final DisplayMetrics dp = getResources().getDisplayMetrics();
    mSize8 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, dp);
    mSize12 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, dp);
    mSize20 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, dp);

    final ViewConfiguration vc = ViewConfiguration.get(ctx);
    mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
    mTouchSlop = vc.getScaledTouchSlop() / 2;
    mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
    mScroller = new OverScroller(ctx);

    int graphBgColor = ContextCompat.getColor(ctx, R.color.tlcDefGraphBackgroundColor);
    int footerBgColor = ContextCompat.getColor(ctx, R.color.tlcDefFooterBackgroundColor);

    mDefFooterBarHeight = mFooterBarHeight = res.getDimension(R.dimen.tlcDefFooterBarHeight);
    mShowFooter = res.getBoolean(R.bool.tlcDefShowFooter);
    mGraphMode = res.getInteger(R.integer.tlcDefGraphMode);
    mPlaySelectionSoundEffect = res.getBoolean(R.bool.tlcDefPlaySelectionSoundEffect);
    mSelectionSoundEffectSource = res.getInteger(R.integer.tlcDefSelectionSoundEffectSource);
    mAnimateCursorTransition = res.getBoolean(R.bool.tlcDefAnimateCursorTransition);
    mFollowCursorPosition = res.getBoolean(R.bool.tlcDefFollowCursorPosition);
    mAlwaysEnsureSelection = res.getBoolean(R.bool.tlcDefAlwaysEnsureSelection);

    mGraphAreaBgPaint = new Paint();
    mGraphAreaBgPaint.setColor(graphBgColor);
    mFooterAreaBgPaint = new Paint();
    mFooterAreaBgPaint.setColor(footerBgColor);
    mTickLabelFgPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
    mTickLabelFgPaint.setFakeBoldText(true);
    mTickLabelFgPaint.setColor(MaterialPaletteHelper.isDarkColor(footerBgColor) ? Color.LTGRAY : Color.DKGRAY);

    mBarItemWidth = res.getDimension(R.dimen.tlcDefBarItemWidth);
    mBarItemSpace = res.getDimension(R.dimen.tlcDefBarItemSpace);

    TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.tlcTimelineChartView, defStyleAttr,
            defStyleRes);
    try {
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.tlcTimelineChartView_tlcGraphBackground) {
                graphBgColor = a.getColor(attr, graphBgColor);
                mGraphAreaBgPaint.setColor(graphBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcShowFooter) {
                mShowFooter = a.getBoolean(attr, mShowFooter);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBackground) {
                footerBgColor = a.getColor(attr, footerBgColor);
                mFooterAreaBgPaint.setColor(footerBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBarHeight) {
                mFooterBarHeight = a.getDimension(attr, mFooterBarHeight);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcGraphMode) {
                mGraphMode = a.getInt(attr, mGraphMode);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAnimateCursorTransition) {
                mAnimateCursorTransition = a.getBoolean(attr, mAnimateCursorTransition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFollowCursorPosition) {
                mFollowCursorPosition = a.getBoolean(attr, mFollowCursorPosition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAlwaysEnsureSelection) {
                mAlwaysEnsureSelection = a.getBoolean(attr, mAlwaysEnsureSelection);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemWidth) {
                mBarItemWidth = a.getDimension(attr, mBarItemWidth);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemSpace) {
                mBarItemSpace = a.getDimension(attr, mBarItemSpace);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcPlaySelectionSoundEffect) {
                mPlaySelectionSoundEffect = a.getBoolean(attr, mPlaySelectionSoundEffect);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcSelectionSoundEffectSource) {
                mSelectionSoundEffectSource = a.getInt(attr, mSelectionSoundEffectSource);
            }
        }
    } finally {
        a.recycle();
    }

    // SurfaceView requires a background
    if (getBackground() == null) {
        setBackgroundColor(ContextCompat.getColor(ctx, android.R.color.transparent));
    }

    // Minimize the impact of create dynamic layouts by assume that in most case
    // we will have a day formatter
    mTickHasDayFormat = true;

    // Initialize stuff
    setupBackgroundHandler();
    setupTickLabels();
    if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
        setupEdgeEffects();
    }
    setupAnimators();
    setupSoundEffects();

    // Initialize the drawing refs (this will be update when we have
    // the real size of the canvas)
    computeBoundAreas();

    // Create a fake data for the edit mode
    if (isInEditMode()) {
        setupViewInEditMode();
    }
}

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   ww  w  .j  a v a 2 s.  c  o 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.juick.android.MessagesFragment.java

public Paint getPaintFromCache(Paint original) {
    if (original instanceof TextPaint) {
        return new TextPaint(original);
    } else {//w  ww . ja  va 2  s  .  co  m
        return new Paint(original);
    }
}