Example usage for android.graphics Canvas drawText

List of usage examples for android.graphics Canvas drawText

Introduction

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

Prototype

public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) 

Source Link

Document

Draw the text, with origin at (x,y), using the specified paint.

Usage

From source file:com.google.android.apps.forscience.whistlepunk.RunReviewOverlay.java

/**
 * Draw a flag above a specific timestamp with a given value, but make sure the flag starts
 * after the given flagXToDrawAfter or that the flag is raised up to avoid intersecting it.
 * @param canvas The canvas to use//from w w w. j  ava 2 s . c om
 * @param pointData The point data to use
 * @param flagMeasurements This set of measurements will be updated in-place to hold the bounds
 *                         of the flag.
 * @param flagXToDrawAfter The x position past which the flag may not draw. If the flag needs
 *                       this space, it must draw itself higher.
 */
private void drawFlagAfter(Canvas canvas, OverlayPointData pointData, FlagMeasurements flagMeasurements,
        float flagXToDrawAfter, boolean drawStem) {
    if (pointData.label == null) {
        pointData.label = "";
    }
    float labelWidth = mTextPaint.measureText(pointData.label);
    String timeLabel = mTimeFormat.formatToTenths(pointData.timestamp - mExternalAxis.getRecordingStartTime());
    float timeWidth = mTimePaint.measureText(timeLabel);

    // Ascent returns the distance above (negative) the baseline (ascent). Since it is negative,
    // negate it again to get the text height.
    float textSize = -1 * mTextPaint.ascent();

    flagMeasurements.boxTop = mHeight - mChartHeight - mPaddingBottom - textSize;
    flagMeasurements.boxBottom = flagMeasurements.boxTop + textSize + mLabelPadding * 2 + 5;
    float width = mIntraLabelPadding + 2 * mLabelPadding + timeWidth + labelWidth;
    // Ideal box layout
    flagMeasurements.boxStart = pointData.screenPoint.x - width / 2;
    flagMeasurements.boxEnd = pointData.screenPoint.x + width / 2;

    // Adjust it if the ideal doesn't work
    boolean isRaised = false;
    if (flagMeasurements.boxStart < flagXToDrawAfter + mCropFlagBufferX) {
        // See if we can simply offset the flag, if it doesn't cause the notch to be drawn
        // off the edge of the flag.
        if (flagXToDrawAfter + mCropFlagBufferX < pointData.screenPoint.x - mNotchHeight * SQRT_2_OVER_2
                - mCornerRadius) {
            flagMeasurements.boxStart = flagXToDrawAfter + mCropFlagBufferX;
            flagMeasurements.boxEnd = flagMeasurements.boxStart + width;
        } else {
            // We need to move the flag up!
            moveUpToAvoid(flagMeasurements, textSize);
            isRaised = true;
        }
    }
    if (flagMeasurements.boxEnd > mWidth) {
        flagMeasurements.boxEnd = mWidth;
        flagMeasurements.boxStart = flagMeasurements.boxEnd - width;
        if (!isRaised && flagXToDrawAfter + mCropFlagBufferX > flagMeasurements.boxStart) {
            // We need to move the flag up!
            moveUpToAvoid(flagMeasurements, textSize);
            isRaised = true;
        }
    }
    flagMeasurements.notchBottom = flagMeasurements.boxBottom + mNotchHeight;

    pointData.labelRect.set(flagMeasurements.boxStart, flagMeasurements.boxTop, flagMeasurements.boxEnd,
            flagMeasurements.boxBottom);
    canvas.drawRoundRect(pointData.labelRect, mCornerRadius, mCornerRadius, mPaint);

    mPath.reset();
    mPath.moveTo((int) (pointData.screenPoint.x - mNotchHeight * SQRT_2_OVER_2), flagMeasurements.boxBottom);
    mPath.lineTo(pointData.screenPoint.x, flagMeasurements.boxBottom + mNotchHeight);
    mPath.lineTo((int) (pointData.screenPoint.x + mNotchHeight * SQRT_2_OVER_2), flagMeasurements.boxBottom);
    canvas.drawPath(mPath, mPaint);

    float textBase = flagMeasurements.boxTop + mLabelPadding + textSize;
    canvas.drawText(timeLabel, flagMeasurements.boxStart + mLabelPadding, textBase, mTimePaint);
    canvas.drawText(pointData.label, flagMeasurements.boxEnd - labelWidth - mLabelPadding, textBase,
            mTextPaint);

    float center = flagMeasurements.boxStart + mLabelPadding + timeWidth + mIntraLabelPadding / 2;
    canvas.drawLine(center, flagMeasurements.boxTop + mLabelPadding, center,
            flagMeasurements.boxBottom - mLabelPadding, mCenterLinePaint);

    if (drawStem) {
        // Draws a vertical line to the flag notch from the base.
        // If there is a flag to draw after, does not overlap that flag.
        if (pointData.screenPoint.x < flagXToDrawAfter) {
            canvas.drawLine(pointData.screenPoint.x, mHeight, pointData.screenPoint.x,
                    mFlagMeasurements.boxBottom - 5 + textSize + 3 * mLabelPadding, mCropVerticalLinePaint);
        } else {
            canvas.drawLine(pointData.screenPoint.x, mHeight, pointData.screenPoint.x,
                    mFlagMeasurements.notchBottom - 5, mCropVerticalLinePaint);
        }
    }
}

From source file:com.example.SmartBoard.DrawingView.java

public void onDrawRectangle(Canvas canvas) {
    Paint paint = drawPaint;/*from w w  w  .jav  a 2  s  .  c om*/
    if (points[3] == null) //point4 null when user did not touch and move on screen.
        return;
    int left, top, right, bottom;
    left = points[0].x;
    top = points[0].y;
    right = points[0].x;
    bottom = points[0].y;
    for (int i = 1; i < points.length; i++) {
        left = left > points[i].x ? points[i].x : left;
        top = top > points[i].y ? points[i].y : top;
        right = right < points[i].x ? points[i].x : right;
        bottom = bottom < points[i].y ? points[i].y : bottom;
    }

    //draw stroke
    paint.setStyle(Paint.Style.STROKE);
    // paint.setColor(Color.parseColor("#AADB1255"));
    paint.setStrokeWidth(5);

    if (finished) {

        Rect rect = new Rect(left + colorballs.get(0).getWidthOfBall() / 2,
                top + colorballs.get(0).getWidthOfBall() / 2, right + colorballs.get(2).getWidthOfBall() / 2,
                bottom + colorballs.get(2).getWidthOfBall() / 2);

        JSONObject objectProperties = new JSONObject();
        String key = UUID.randomUUID().toString();

        try {
            objectProperties.put("type", "Rectangle");
            objectProperties.put("clientId", client.getClientId());
            objectProperties.put("id", key);
            objectProperties.put("color", drawPaint.getColor());
            objectProperties.put("size", 5);
            objectProperties.put("dimens", rect.flattenToString());

        } catch (JSONException e) {

        }

        objectDrawables.put(key, objectProperties);

        mqtt.publishRectangle(objectProperties);
        //reset to start drawing again
        points = new Point[4];
        colorballs.clear();
        return;
    }

    //temporary canvas drawing on resize mode
    canvas.drawRect(left + colorballs.get(0).getWidthOfBall() / 2, top + colorballs.get(0).getWidthOfBall() / 2,
            right + colorballs.get(2).getWidthOfBall() / 2, bottom + colorballs.get(2).getWidthOfBall() / 2,
            paint);

    //draw the corners
    BitmapDrawable bitmap = new BitmapDrawable();
    // draw the balls on the canvas
    paint.setTextSize(18);
    paint.setStrokeWidth(0);

    for (int i = 0; i < colorballs.size(); i++) {
        ColorBall ball = colorballs.get(i);
        canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), paint);
        //  System.out.println("RectMode");

        canvas.drawText("" + (i + 1), ball.getX(), ball.getY(), paint);
    }
}

From source file:com.pdftron.pdf.tools.Tool.java

public void onDraw(Canvas canvas, android.graphics.Matrix tfm) {
    // Draw page number
    if (mShowPageNum && mPageNumberIndicatorVisible) {
        int width = mPDFView.getWidth();
        int height = mPDFView.getHeight();
        int page_num = mPDFView.getCurrentPage();
        boolean restore = false;
        float yOffset = 0;

        try {//  w w  w .  ja  v a  2 s  .c  om
            // During page sliding, PDFViewCtrl might apply extra transformation
            // matrix to Canvas for animation. However, page number should not
            // move; hence applying the inverse to offset it.
            if (!tfm.isIdentity()) {
                canvas.save();
                restore = true;
                tfm.invert(mTempMtx1);
                canvas.getMatrix(mTempMtx2);
                mTempMtx2.postConcat(mTempMtx1);
                canvas.setMatrix(mTempMtx2);

                // Workaround for bug found in Android > ICS with hardware acceleration turned
                // ON. See http://code.google.com/p/android/issues/detail?id=24517 for more info
                if (Build.VERSION.SDK_INT >= 14
                        /*Build.VERSION_CODES.ICE_CREAM_SANDWICH*/ && mPDFView.isHardwareAccelerated()) {
                    Rect rectangle = new Rect();
                    ((android.app.Activity) mPDFView.getContext()).getWindow().getDecorView()
                            .getWindowVisibleDisplayFrame(rectangle);
                    yOffset = rectangle.top;
                }
            }

            int page_count = mPDFView.getDoc().getPageCount();
            String str = String.format(getStringFromResId(R.string.tools_misc_pagerange), page_num, page_count);

            Rect r = new Rect();
            mPaint4PageNum.getTextBounds(str, 0, str.length(), r);
            float str_width = r.width();
            float str_height = r.height();

            float margin = str_height / 1.5f;
            float left = width - str_width * 1.5f - margin + mPDFView.getScrollX();

            float top = mPDFView.getScrollY() + height - mPageNumPosAdjust - str_height * 3.0f + yOffset;

            float right = left + str_width + margin * 2;
            float bottom = top + str_height + margin * 2;

            mTempPageDrawingRectF.set(left, top, right, bottom);
            mPaint4PageNum.setColor(
                    mPDFView.getContext().getResources().getColor(R.color.tools_pageindicator_background));
            canvas.drawRoundRect(mTempPageDrawingRectF, margin, margin, mPaint4PageNum);

            mPaint4PageNum
                    .setColor(mPDFView.getContext().getResources().getColor(R.color.tools_pageindicator_text));
            left += margin;
            top += str_height / 2 + margin + mPaint4PageNum.descent();

            canvas.drawText(str, left, top - 0.5f, mPaint4PageNum);

        } catch (Exception e) {

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

From source file:fr.magistry.taigime.CandidateView.java

/**
 * If the canvas is null, then only touch calculations are performed to pick the target
 * candidate./*from   ww  w  .  ja v  a  2  s  .  co  m*/
 */
@Override
protected void onDraw(Canvas canvas) {
    if (canvas != null) {
        super.onDraw(canvas);
    }
    mTotalWidth = 0;
    if (mSuggestions == null)
        return;

    if (mBgPadding == null) {
        mBgPadding = new Rect(0, 0, 0, 0);
        if (getBackground() != null) {
            getBackground().getPadding(mBgPadding);
        }
    }
    int x = 0;
    final int count = mSuggestions.size();
    final int height = getHeight();
    final Rect bgPadding = mBgPadding;
    final Paint paint = mPaint;
    final int touchX = mTouchX;
    final int scrollX = getScrollX();
    final boolean scrolled = mScrolled;
    final int y; //= (int) ( - mPaint.ascent() + mVerticalPadding);
    final int y2; //= (int) (height - mPaintTRS.descent()); // (y - mVerticalPadding - mPaint.descent() - mPaintTRS.ascent()) ;
    final float initialTRSsize = mPaintTRS.getTextSize();
    if (mOutputTRS) {
        y2 = (int) (-mPaintTRS.ascent() + mVerticalPadding);
        y = (int) (height - mPaint.descent());

    } else {
        y = (int) (-mPaint.ascent() + mVerticalPadding);
        y2 = (int) (height - mPaintTRS.descent());

    }
    for (int i = 0; i < count; i++) {
        Candidate suggestion = mSuggestions.get(i);
        String hanji = suggestion.getWord().getHanji();
        String trs = "";
        switch (ROMANISATION_OUTPUT_MODE) {
        case 0:
            trs = suggestion.getWord().getTailuo();
            break;
        case 1:
            trs = suggestion.getWord().getPOJ();
            break;
        case 2:
            trs = suggestion.getWord().getPOJ_safe();
            break;
        default:
            trs = suggestion.getWord().getTailuo();
        }
        float textWidth;
        if (i == 0) {
            hanji = "";
            trs = "";//hanji;//TODO: conversion?
            //if(mOutputTRS){
            trs = suggestion.getWord().getBopomo();
            if (trs != "")
                textWidth = mPaintBPM.measureText(trs);
            else
                textWidth = 3;
            //}
            //else {
            //   hanji = suggestion.getWord().getBopomo();
            //   textWidth = paint.measureText(hanji);
            //}
        } else
            textWidth = paint.measureText(hanji);
        if (textWidth == 0.0)
            textWidth = paint.measureText(" ");

        final int wordWidth = (int) textWidth + X_GAP * 2;
        mWordX[i] = x;
        mWordWidth[i] = wordWidth;
        mPaintTRS.setTextSize(initialTRSsize);
        mPaintTRS.setTextSize(reduceTextSizeFromWidth(mPaintTRS, trs, textWidth));
        paint.setColor(mColorNormal);
        if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) {
            if (canvas != null) {
                canvas.translate(x, 0);
                mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
                mSelectionHighlight.draw(canvas);
                canvas.translate(-x, 0);
            }
            mSelectedIndex = i;
        }

        if (canvas != null) {
            Paint activePaint = null;
            Paint secondPaint = null;
            if (mOutputTRS) {
                activePaint = mPaintTRS;
                secondPaint = paint;
            } else {
                activePaint = paint;
                secondPaint = mPaintTRS;
            }
            if (i == 0) {
                activePaint = mPaintBPM;
            }
            secondPaint.setAlpha(150);
            if ((i == mCursor)) {
                activePaint.setFakeBoldText(true);
                activePaint.setColor(mColorRecommended);
            } else if (i != 0) {
                activePaint.setColor(mColorOther);
            }
            if (i == 0) {
                canvas.drawText(trs, x + X_GAP, y2, mPaintBPM);
            } else {
                canvas.drawText(hanji, x + X_GAP, y, paint);
                canvas.drawText(trs, x + X_GAP, y2, mPaintTRS);
            }
            activePaint.setColor(mColorOther);
            canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1, paint);
            activePaint.setFakeBoldText(false);
            secondPaint.setAlpha(255);
        }
        x += wordWidth;
        mPaintTRS.setTextSize(initialTRSsize);
    }
    mTotalWidth = x;
    if (mTargetScrollX != getScrollX()) {
        scrollToTarget();
    }
}

From source file:com.jjoe64.graphview.GridLabelRenderer.java

/**
 * draws the horizontal steps/*from  w w w  . j a v a  2  s .  c  o  m*/
 * vertical lines and horizontal labels
 *
 * @param canvas canvas
 */
protected void drawHorizontalSteps(Canvas canvas) {
    // draw horizontal steps (vertical lines and horizontal labels)
    mPaintLabel.setColor(getHorizontalLabelsColor());
    int i = 0;
    for (Map.Entry<Integer, Double> e : mStepsHorizontal.entrySet()) {
        // draw line
        if (mStyles.highlightZeroLines) {
            if (e.getValue() == 0d) {
                mPaintLine.setStrokeWidth(5);
            } else {
                mPaintLine.setStrokeWidth(0);
            }
        }
        if (mStyles.gridStyle.drawVertical()) {
            canvas.drawLine(mGraphView.getGraphContentLeft() + e.getKey(), mGraphView.getGraphContentTop(),
                    mGraphView.getGraphContentLeft() + e.getKey(),
                    mGraphView.getGraphContentTop() + mGraphView.getGraphContentHeight(), mPaintLine);
        }

        // draw label
        if (isHorizontalLabelsVisible()) {
            if (mStyles.horizontalLabelsAngle > 0f && mStyles.horizontalLabelsAngle <= 180f) {
                if (mStyles.horizontalLabelsAngle < 90f) {
                    mPaintLabel.setTextAlign((Paint.Align.RIGHT));
                } else if (mStyles.horizontalLabelsAngle <= 180f) {
                    mPaintLabel.setTextAlign((Paint.Align.LEFT));
                }
            } else {
                mPaintLabel.setTextAlign(Paint.Align.CENTER);
                if (i == mStepsHorizontal.size() - 1)
                    mPaintLabel.setTextAlign(Paint.Align.RIGHT);
                if (i == 0)
                    mPaintLabel.setTextAlign(Paint.Align.LEFT);
            }

            // multiline labels
            String label = mLabelFormatter.formatLabel(e.getValue(), true);
            if (label == null) {
                label = "";
            }
            String[] lines = label.split("\n");

            // If labels are angled, calculate adjustment to line them up with the grid
            int labelWidthAdj = 0;
            if (mStyles.horizontalLabelsAngle > 0f && mStyles.horizontalLabelsAngle <= 180f) {
                Rect textBounds = new Rect();
                mPaintLabel.getTextBounds(lines[0], 0, lines[0].length(), textBounds);
                labelWidthAdj = (int) Math
                        .abs(textBounds.width() * Math.cos(Math.toRadians(mStyles.horizontalLabelsAngle)));
            }
            for (int li = 0; li < lines.length; li++) {
                // for the last line y = height
                float y = (canvas.getHeight() - mStyles.padding - getHorizontalAxisTitleHeight())
                        - (lines.length - li - 1) * getTextSize() * 1.1f + mStyles.labelsSpace;
                float x = mGraphView.getGraphContentLeft() + e.getKey();
                if (mStyles.horizontalLabelsAngle > 0 && mStyles.horizontalLabelsAngle < 90f) {
                    canvas.save();
                    canvas.rotate(mStyles.horizontalLabelsAngle, x + labelWidthAdj, y);
                    canvas.drawText(lines[li], x + labelWidthAdj, y, mPaintLabel);
                    canvas.restore();
                } else if (mStyles.horizontalLabelsAngle > 0 && mStyles.horizontalLabelsAngle <= 180f) {
                    canvas.save();
                    canvas.rotate(mStyles.horizontalLabelsAngle - 180f, x - labelWidthAdj, y);
                    canvas.drawText(lines[li], x - labelWidthAdj, y, mPaintLabel);
                    canvas.restore();
                } else {
                    canvas.drawText(lines[li], x, y, mPaintLabel);
                }
            }
        }
        i++;
    }
}

From source file:com.cssweb.android.view.KlineView.java

public void drawCCI(Canvas canvas, JSONObject quoteData, int begin, int count, double shapeWidth,
        double spaceWidth, double highPrice, double lowPrice, double highVolume, int actualDataLen)
        throws JSONException {
    if (quoteData.isNull("CCI") || quoteData.getJSONArray("CCI").length() < 1) {
        isNetworkErrorDisplay();//from w  ww  .j a  va 2s  .  c o m
        return;
    }

    //this.shapeWidth = shapeWidth;
    //this.spaceWidth = spaceWidth;

    double max = 0.001;
    double min = -0.001;
    for (int i = begin; i < (begin + count); i++) {
        double cci = quoteData.getJSONArray("CCI").getJSONArray(i).getDouble(1);
        max = Math.max(cci, max);
        min = Math.min(cci, min);
    }

    double scale = this.volumeHeight / (Math.max(100, max) + Math.max(Math.abs(min), 100));

    int axisY100 = (int) (klineY + volumeHeight - (100 + Math.abs(min)) * scale);
    paint.setColor(GlobalColor.clrLine);
    Graphics.drawDashline(canvas, klineX, axisY100, width, axisY100, paint);

    int axisY0 = (int) (klineY + volumeHeight - (0 + Math.abs(min)) * scale);
    Graphics.drawDashline(canvas, klineX, axisY0, width, axisY0, paint);

    int axisYM100 = (int) (klineY + volumeHeight - (Math.abs(min) - 100) * scale);
    Graphics.drawDashline(canvas, klineX, axisYM100, width, axisYM100, paint);

    if (isTrackStatus == false) {
        tPaint.setColor(GlobalColor.colorKlabel);
        canvas.drawText("100.00", klineX - tips / 4, axisY100 + axisLabelHeight / 2, tPaint);
        canvas.drawText("0.00", klineX - tips / 4, axisY0 + axisLabelHeight / 2, tPaint);
        canvas.drawText("-100.00", klineX - tips / 4, axisYM100 + axisLabelHeight / 2, tPaint);
    }
    canvas.drawLine(klineX, height - axisLabelHeight, width, height - axisLabelHeight, paint);

    if (quoteData != null) {
        double axisX = 0;
        double difx = 0;

        //double deax = 0;
        //double jx = 0;

        int kHeight = 0;
        int ky = 0;
        //int dHeight = 0;
        //int dy = 0;               
        //int jHeight = 0;
        //int jy = 0;               

        paint.setColor(GlobalColor.colorM5);
        for (int i = begin; i < (begin + count); i++) {
            double cci = quoteData.getJSONArray("CCI").getJSONArray(i).getDouble(1);

            //klineX = 0;
            if ((i - begin) == 0)
                axisX = axisX + klineX + spaceWidth;
            else
                axisX = axisX + spaceWidth + shapeWidth;

            if ((i - begin) == 0) {
                difx = difx + klineX + spaceWidth + shapeWidth / 2;
                kHeight = (int) ((cci + Math.abs(min)) * scale);
                //kHeight = cci * scale;
                ky = klineY + volumeHeight - kHeight;
            } else {
                double x1 = difx;
                int y1 = ky;
                difx = difx + spaceWidth + shapeWidth;
                kHeight = (int) ((cci + Math.abs(min)) * scale);
                ky = klineY + volumeHeight - kHeight;

                canvas.drawLine((int) x1, y1, (int) difx, ky, paint);
            }

            if (i == (begin + count - 1)) {
                //labelDif.text = "CCI:" + Utils.StockFormat(exchange+stockCode, cci);
            }
        } // end for
    } // end if
}

From source file:com.lovely3x.eavlibrary.EasyAdapterView.java

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    drawDivider(canvas);/*from  ww  w .j  a  va2  s. c om*/
    if (DEBUG) {
        switch (mLayoutDirectly) {
        case LAYOUT_DIRECTLY_HORIZONTAL:
            canvas.drawLine(getXSel(), 0, getXSel(), getHeight(), mDebugPaint);
            break;
        case LAYOUT_DIRECTLY_VERTICAL:
            canvas.drawLine(0, getYSel(), getWidth(), getYSel(), mDebugPaint);
            break;
        }
        canvas.drawText(String.valueOf(mFirstPosition), 100, 100, mDebugPaint);
    }

}

From source file:com.jakewharton.android.viewpagerindicator.TitlePageIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //Calculate views bounds
    ArrayList<RectF> bounds = calculateAllBounds(mPaintText);

    final int count = mViewPager.getAdapter().getCount();
    final int countMinusOne = count - 1;
    final float halfWidth = getWidth() / 2f;
    final int left = getLeft();
    final float leftClip = left + mClipPadding;
    final int width = getWidth();
    final int height = getHeight();
    final int right = left + width;
    final float rightClip = right - mClipPadding;

    int page = mCurrentPage;
    float offsetPercent;
    if (mCurrentOffset <= halfWidth) {
        offsetPercent = 1.0f * mCurrentOffset / width;
    } else {/*from w w  w  .j  a  va2 s.c  o m*/
        page += 1;
        offsetPercent = 1.0f * (width - mCurrentOffset) / width;
    }
    final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
    final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);
    final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE;

    //Verify if the current view must be clipped to the screen
    RectF curPageBound = bounds.get(mCurrentPage);
    float curPageWidth = curPageBound.right - curPageBound.left;
    if (curPageBound.left < leftClip) {
        //Try to clip to the screen (left side)
        clipViewOnTheLeft(curPageBound, curPageWidth, left);
    }
    if (curPageBound.right > rightClip) {
        //Try to clip to the screen (right side)
        clipViewOnTheRight(curPageBound, curPageWidth, right);
    }

    //Left views starting from the current position
    if (mCurrentPage > 0) {
        for (int i = mCurrentPage - 1; i >= 0; i--) {
            RectF bound = bounds.get(i);
            //Is left side is outside the screen
            if (bound.left < leftClip) {
                float w = bound.right - bound.left;
                //Try to clip to the screen (left side)
                clipViewOnTheLeft(bound, w, left);
                //Except if there's an intersection with the right view
                RectF rightBound = bounds.get(i + 1);
                //Intersection
                if (bound.right + mTitlePadding > rightBound.left) {
                    bound.left = rightBound.left - w - mTitlePadding;
                    bound.right = bound.left + w;
                }
            }
        }
    }
    //Right views starting from the current position
    if (mCurrentPage < countMinusOne) {
        for (int i = mCurrentPage + 1; i < count; i++) {
            RectF bound = bounds.get(i);
            //If right side is outside the screen
            if (bound.right > rightClip) {
                float w = bound.right - bound.left;
                //Try to clip to the screen (right side)
                clipViewOnTheRight(bound, w, right);
                //Except if there's an intersection with the left view
                RectF leftBound = bounds.get(i - 1);
                //Intersection
                if (bound.left - mTitlePadding < leftBound.right) {
                    bound.left = leftBound.right + mTitlePadding;
                    bound.right = bound.left + w;
                }
            }
        }
    }

    //Now draw views
    for (int i = 0; i < count; i++) {
        //Get the title
        RectF bound = bounds.get(i);
        //Only if one side is visible
        if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) {
            final boolean currentPage = (i == page);
            //Only set bold if we are within bounds
            mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText);

            //Draw text as unselected
            mPaintText.setColor(mColorText);
            canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom, mPaintText);

            //If we are within the selected bounds draw the selected text
            if (currentPage && currentSelected) {
                mPaintText.setColor(mColorSelected);
                mPaintText.setAlpha((int) ((mColorSelected >>> 24) * selectedPercent));
                canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom, mPaintText);
            }
        }
    }

    //Draw the footer line
    mPath = new Path();
    mPath.moveTo(0, height - mFooterLineHeight);
    mPath.lineTo(width, height - mFooterLineHeight);
    mPath.close();
    canvas.drawPath(mPath, mPaintFooterLine);

    switch (mFooterIndicatorStyle) {
    case Triangle:
        mPath = new Path();
        mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.close();
        canvas.drawPath(mPath, mPaintFooterIndicator);
        break;

    case Underline:
        if (!currentSelected) {
            break;
        }

        RectF underlineBounds = bounds.get(page);
        mPath = new Path();
        mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
        mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
        mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding,
                height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding,
                height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.close();

        mPaintFooterIndicator.setAlpha((int) (0xFF * selectedPercent));
        canvas.drawPath(mPath, mPaintFooterIndicator);
        mPaintFooterIndicator.setAlpha(0xFF);
        break;
    }
}

From source file:com.androtex.viewpagerindicator.TitlePageIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //Calculate views bounds
    ArrayList<RectF> bounds = calculateAllBounds(mPaintText);

    final int count = mViewPager.getAdapter().getCount();
    final int countMinusOne = count - 1;
    final float halfWidth = getWidth() / 2f;
    final int left = getLeft();
    final float leftClip = left + mClipPadding;
    final int width = getWidth();
    final int height = getHeight();
    final int right = left + width;
    final float rightClip = right - mClipPadding;

    int page = mCurrentPage;
    float offsetPercent;
    if (mCurrentOffset <= halfWidth) {
        offsetPercent = 1.0f * mCurrentOffset / width;
    } else {/*from w  w w  .j a v a 2 s.  c o m*/
        page += 1;
        offsetPercent = 1.0f * (width - mCurrentOffset) / width;
    }
    final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
    final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);
    final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE;

    //Verify if the current view must be clipped to the screen
    RectF curPageBound = bounds.get(mCurrentPage);
    float curPageWidth = curPageBound.right - curPageBound.left;
    if (curPageBound.left < leftClip) {
        //Try to clip to the screen (left side)
        clipViewOnTheLeft(curPageBound, curPageWidth, left);
    }
    if (curPageBound.right > rightClip) {
        //Try to clip to the screen (right side)
        clipViewOnTheRight(curPageBound, curPageWidth, right);
    }

    //Left views starting from the current position
    if (mCurrentPage > 0) {
        for (int i = mCurrentPage - 1; i >= 0; i--) {
            RectF bound = bounds.get(i);
            //Is left side is outside the screen
            if (bound.left < leftClip) {
                float w = bound.right - bound.left;
                //Try to clip to the screen (left side)
                clipViewOnTheLeft(bound, w, left);
                //Except if there's an intersection with the right view
                RectF rightBound = bounds.get(i + 1);
                //Intersection
                if (bound.right + mTitlePadding > rightBound.left) {
                    bound.left = rightBound.left - w - mTitlePadding;
                    bound.right = bound.left + w;
                }
            }
        }
    }
    //Right views starting from the current position
    if (mCurrentPage < countMinusOne) {
        for (int i = mCurrentPage + 1; i < count; i++) {
            RectF bound = bounds.get(i);
            //If right side is outside the screen
            if (bound.right > rightClip) {
                float w = bound.right - bound.left;
                //Try to clip to the screen (right side)
                clipViewOnTheRight(bound, w, right);
                //Except if there's an intersection with the left view
                RectF leftBound = bounds.get(i - 1);
                //Intersection
                if (bound.left - mTitlePadding < leftBound.right) {
                    bound.left = leftBound.right + mTitlePadding;
                    bound.right = bound.left + w;
                }
            }
        }
    }

    //Now draw views
    for (int i = 0; i < count; i++) {
        //Get the title
        RectF bound = bounds.get(i);
        //Only if one side is visible
        if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) {
            final boolean currentPage = (i == page);
            //Only set bold if we are within bounds
            mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText);

            //Draw text as unselected
            mPaintText.setColor(mColorText);
            canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText);

            //If we are within the selected bounds draw the selected text
            if (currentPage && currentSelected) {
                mPaintText.setColor(mColorSelected);
                mPaintText.setAlpha((int) ((mColorSelected >>> 24) * selectedPercent));
                canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText);
            }
        }
    }

    //Draw the footer line
    mPath = new Path();
    mPath.moveTo(0, height - mFooterLineHeight / 2f);
    mPath.lineTo(width, height - mFooterLineHeight / 2f);
    mPath.close();
    canvas.drawPath(mPath, mPaintFooterLine);

    switch (mFooterIndicatorStyle) {
    case Triangle:
        mPath = new Path();
        mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.close();
        canvas.drawPath(mPath, mPaintFooterIndicator);
        break;

    case Underline:
        if (!currentSelected) {
            break;
        }

        RectF underlineBounds = bounds.get(page);
        mPath = new Path();
        mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
        mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
        mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding,
                height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding,
                height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.close();

        mPaintFooterIndicator.setAlpha((int) (0xFF * selectedPercent));
        canvas.drawPath(mPath, mPaintFooterIndicator);
        mPaintFooterIndicator.setAlpha(0xFF);
        break;
    }
}

From source file:com.jjoe64.graphview.series.TitleLineGraphSeries.java

@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
    paint.setColor(getColor());/*from   ww w .  ja  va2s.  c  om*/
    paint.setStrokeWidth(thickness);
    paintBackground.setColor(backgroundColor);
    pathBackground.reset();

    resetDataPoints();

    // get data
    double maxX = graphView.getViewport().getMaxX(false);
    double minX = graphView.getViewport().getMinX(false);

    double maxY;
    double minY;
    if (isSecondScale) {
        maxY = graphView.getSecondScale().getMaxY();
        minY = graphView.getSecondScale().getMinY();
    } else {
        maxY = graphView.getViewport().getMaxY(false);
        minY = graphView.getViewport().getMinY(false);
    }

    // draw data
    double diffY = maxY - minY;
    double diffX = maxX - minX;

    float graphHeight = graphView.getGraphContentHeight();
    float graphWidth = graphView.getGraphContentWidth();
    float graphLeft = graphView.getGraphContentLeft();
    float graphTop = graphView.getGraphContentTop();

    // draw background
    double lastEndY = 0;
    double lastEndX = 0;

    double titleY = 0;

    double lastUsedEndX = 0;
    float firstX = 0;
    int i = 0;
    Iterator<E> values = getValues(minX, maxX);
    while (values.hasNext()) {
        E value = values.next();

        double valY = value.getY() - minY;
        double ratY = valY / diffY;
        double y = graphHeight * ratY;

        double valX = value.getX() - minX;
        double ratX = valX / diffX;
        double x = graphWidth * ratX;

        double orgX = x;
        double orgY = y;

        if (i > 0) {
            // overdraw
            if (x > graphWidth) { // end right
                double b = ((graphWidth - lastEndX) * (y - lastEndY) / (x - lastEndX));
                y = lastEndY + b;
                x = graphWidth;
            }
            if (y < 0) { // end bottom
                double b = ((0 - lastEndY) * (x - lastEndX) / (y - lastEndY));
                x = lastEndX + b;
                y = 0;
            }
            if (y > graphHeight) { // end top
                double b = ((graphHeight - lastEndY) * (x - lastEndX) / (y - lastEndY));
                x = lastEndX + b;
                y = graphHeight;
            }
            if (lastEndY < 0) { // start bottom
                double b = ((0 - y) * (x - lastEndX) / (lastEndY - y));
                lastEndX = x - b;
                lastEndY = 0;
            }
            if (lastEndX < 0) { // start left
                double b = ((0 - x) * (y - lastEndY) / (lastEndX - x));
                lastEndY = y - b;
                lastEndX = 0;
            }
            if (lastEndY > graphHeight) { // start top
                double b = ((graphHeight - y) * (x - lastEndX) / (lastEndY - y));
                lastEndX = x - b;
                lastEndY = graphHeight;
            }

            float startX = (float) lastEndX + (graphLeft + 1);
            float startY = (float) (graphTop - lastEndY) + graphHeight;
            float endX = (float) x + (graphLeft + 1);
            float endY = (float) (graphTop - y) + graphHeight;

            registerDataPoint(endX, endY, value);

            path.reset();
            path.moveTo(startX, startY);
            path.lineTo(endX, endY);
            canvas.drawPath(path, paint);
            if (i == 1) {
                firstX = startX;
                pathBackground.moveTo(startX, startY);
            }
            pathBackground.lineTo(endX, endY);
            lastUsedEndX = endX;
        }
        lastEndY = orgY;
        lastEndX = orgX;
        titleY = Math.max(titleY, orgY);
        i++;
    }

    pathBackground.lineTo((float) lastUsedEndX, graphHeight + graphTop);
    pathBackground.lineTo(firstX, graphHeight + graphTop);
    pathBackground.close();
    canvas.drawPath(pathBackground, paintBackground);

    if (StringUtils.isNotBlank(getTitle()) && lastUsedEndX > 0) {
        float x = (float) (lastUsedEndX + firstX) / 2;
        float y = (float) (graphTop - titleY) + graphHeight - 10;

        paintTitle.setColor(getColor());
        paintTitle.setTextSize(graphView.getLegendRenderer().getTextSize());
        paintTitle.setFakeBoldText(textBold);
        canvas.drawText(getTitle(), x, y, paintTitle);
    }
}