Example usage for android.graphics Canvas drawPath

List of usage examples for android.graphics Canvas drawPath

Introduction

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

Prototype

public void drawPath(@NonNull Path path, @NonNull Paint paint) 

Source Link

Document

Draw the specified path using the specified paint.

Usage

From source file:com.brian.common.view.DrawerArrowDrawable.java

@Override
public void draw(Canvas canvas) {
    if (mIsCirculate) {
        if (mProgress >= .995) {
            flipped = true;//w ww. ja  v a  2 s  .com
        } else if (mProgress <= .005) {
            flipped = false;
        }
        if (flipped) {
            canvas.save();
            canvas.scale(1f, -1f, getIntrinsicWidth() / 2, getIntrinsicHeight() / 2);
        }
    }

    Rect bounds = getBounds();

    final boolean flipToPointRight;
    switch (mDirection) {
    case ARROW_DIRECTION_LEFT:
        flipToPointRight = false;
        break;
    case ARROW_DIRECTION_RIGHT:
        flipToPointRight = true;
        break;
    default:
        flipToPointRight = false;
        break;
    }

    // Interpolated widths of arrow bars

    float arrowHeadBarLength = (float) Math.sqrt(mArrowHeadLength * mArrowHeadLength * 2);
    arrowHeadBarLength = lerp(mBarLength, arrowHeadBarLength, mProgress);
    final float arrowShaftLength = lerp(mBarLength, mArrowShaftLength, mProgress);
    // Interpolated size of middle bar
    final float arrowShaftCut = Math.round(lerp(0, mMaxCutForBarSize, mProgress));
    // The rotation of the top and bottom bars (that make the arrow head)
    final float rotation = lerp(0, ARROW_HEAD_ANGLE, mProgress);

    // The whole canvas rotates as the transition happens
    final float canvasRotate = lerp(flipToPointRight ? 0 : -180, flipToPointRight ? 180 : 0, mProgress);

    final float arrowWidth = Math.round(arrowHeadBarLength * Math.cos(rotation));
    final float arrowHeight = Math.round(arrowHeadBarLength * Math.sin(rotation));

    mPath.rewind();
    final float topBottomBarOffset = lerp(mBarGap + mPaint.getStrokeWidth(), -mMaxCutForBarSize, mProgress);

    final float arrowEdge = -arrowShaftLength / 2;
    // draw middle bar
    mPath.moveTo(arrowEdge + arrowShaftCut, 0);
    mPath.rLineTo(arrowShaftLength - arrowShaftCut * 2, 0);

    // bottom bar
    mPath.moveTo(arrowEdge, topBottomBarOffset);
    mPath.rLineTo(arrowWidth, arrowHeight);

    // top bar
    mPath.moveTo(arrowEdge, -topBottomBarOffset);
    mPath.rLineTo(arrowWidth, -arrowHeight);

    mPath.close();

    canvas.save();

    // Rotate the whole canvas if spinning, if not, rotate it 180 to get
    // the arrow pointing the other way for RTL.
    final float barThickness = mPaint.getStrokeWidth();
    final int remainingSpace = (int) (bounds.height() - barThickness * 3 - mBarGap * 2);
    float yOffset = (remainingSpace / 4) * 2; // making sure it is a multiple of 2.
    yOffset += barThickness * 1.5 + mBarGap;

    canvas.translate(bounds.centerX(), yOffset);
    if (mSpin) {
        canvas.rotate(canvasRotate * ((mVerticalMirror ^ flipToPointRight) ? -1 : 1));
    } else if (flipToPointRight) {
        canvas.rotate(180);
    }
    canvas.drawPath(mPath, mPaint);

    canvas.restore();
}

From source file:com.acceleratedio.pac_n_zoom.DrawSVG.java

public ArrayList<ImageView> DrawSVG(Context context, ImageView orgnlImageView, RelativeLayout rel_anm_lo) {

    paint.setColor(Color.WHITE);//from   www . j  a v  a  2  s .  c  o  m
    paint.setStyle(Paint.Style.FILL);
    LoadSVG.SVGData data = AnimActivity.svg_data;
    ArrayList<ImageView> imgViews = new ArrayList<ImageView>();
    imgViews.add(orgnlImageView);

    if (data.symbl != null) {

        ArrayList<String> sprt_ordr = data.svg.ordr;
        int sym_mbr = 0;
        Bitmap bitmap;
        Canvas canvas;

        // - Loop through the sprites 
        int sprt_nmbr = sprt_ordr.size();
        data.svg.initScl = new float[sprt_nmbr];
        float[] initScl = data.svg.initScl;

        for (int sprt_mbr = 1; sprt_mbr < sprt_nmbr; sprt_mbr += 1) {

            String sprt_id = sprt_ordr.get(sprt_mbr); // e.g., id="g2_0"

            if (Integer.parseInt(sprt_id.substring(sprt_id.indexOf('_') + 1)) > 0) {
                // The symbol is already drawn; replicate the view   
                String init_sprt = sprt_id.substring(0, sprt_id.indexOf('_') + 1) + '0';
                String svg_ordr = data.svg.svg_ordr;
                String cnt_str = svg_ordr.substring(0, svg_ordr.indexOf(init_sprt));
                ImageView init_vw = imgViews.get(StringUtils.countMatches(cnt_str, ","));
                Bitmap initBmp = ((BitmapDrawable) init_vw.getDrawable()).getBitmap();

                bitmap = Bitmap.createBitmap(initBmp.getWidth(), initBmp.getHeight(), initBmp.getConfig());

                canvas = new Canvas(bitmap);
                canvas.save(Canvas.MATRIX_SAVE_FLAG);
                xfrmInit crt_sprt = getInitSpriteAttrib(sprt_id);
                canvas.scale(crt_sprt.scl, crt_sprt.scl);
                initScl[sprt_mbr] = crt_sprt.scl;
                canvas.translate(0, 0);
            } else {
                // The symbol needs to be drawn; a new view   is used
                bitmap = getCreatBmp(rel_anm_lo);
                canvas = new Canvas(bitmap);
                canvas.save(Canvas.MATRIX_SAVE_FLAG);

                // - Set the init values
                xfrmInit crt_sprt = getInitSpriteAttrib(sprt_id);
                canvas.scale(crt_sprt.scl, crt_sprt.scl);
                initScl[sprt_mbr] = crt_sprt.scl;
                canvas.translate(0, 0);

                // - Draw the bitmap
                LoadSVG.symbol crt_sym = data.symbl.get(sym_mbr);
                ArrayList<LoadSVG.path> pths = crt_sym.pths;
                int pth_nmbr = pths.size();

                // Loop through the paths
                for (int pth_mbr = 0; pth_mbr < pth_nmbr; pth_mbr += 1) {

                    LoadSVG.path crt_pth = pths.get(pth_mbr);
                    final Path path = new Path();
                    final Paint paint = new Paint();
                    /* Debug
                    if (pth_mbr + 1 == pth_nmbr) {
                            
                       String log_str = "Paths: pth_mbr = " +
                          String.valueOf(pth_mbr) + "; color = " + crt_pth.clr;
                            
                       Log.d("DrawSVG", log_str);
                    }
                    */
                    paint.setColor(Color.parseColor(crt_pth.clr));
                    paint.setAntiAlias(true);
                    paint.setStyle(Paint.Style.FILL_AND_STROKE);
                    ld_pth_pnts(crt_pth.pth, path);
                    path.close();
                    path.setFillType(Path.FillType.EVEN_ODD);
                    canvas.drawPath(path, paint);
                }

                canvas.restore();
                sym_mbr += 1;
            }

            ImageView iv = new ImageView(context);
            iv.setImageBitmap(bitmap);

            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

            iv.draw(canvas);
            iv.setLayoutParams(rlp);
            iv.setBackgroundColor(Color.TRANSPARENT);
            imgViews.add(iv);
        } // sprites
    } // if symbol

    return imgViews;
}

From source file:com.icloud.listenbook.base.view.viewpagerindicator.FixedTitlePageIndicator.java

private void onDrawIsFixedTitle(Canvas canvas) {
    // // www  .ja  va2s  .co m
    bounds = calculateFixedAllBounds(mPaintText);
    // 
    final int count = mViewPager.getAdapter().getCount();
    final float unitNum = (count > 3 ? 4f : count);
    final float halfWidth = getWidth() / 2f;
    final float unitWidth = getWidth() / unitNum;
    final int left = getLeft();
    final int width = getWidth();
    final int height = getHeight();
    final int right = left + width;
    int page = mCurrentPage;
    float offsetPercent;
    if (mCurrentOffset <= halfWidth) {
        offsetPercent = 1.0f * mCurrentOffset / width;
    } else {
        page += 1;
        offsetPercent = 1.0f * (width - mCurrentOffset) / width;
    }

    final float mOffset = unitWidth * (1.0f * mCurrentOffset / width);
    final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
    final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);
    final float selectedPercent = (0.5f - offsetPercent) / 0.5f;

    // 
    RectF curPageBound = bounds.get(mCurrentPage);
    final float curPageW = curPageBound.right - curPageBound.left;
    // 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.getPageTitle(i).toString(), bound.left, bound.bottom + mTopPadding,
                    mPaintText);

            // 
            if (currentPage && currentSelected) {
                mPaintText.setColor(mColorSelected);
                mPaintText.setAlpha((int) ((mColorSelected >>> 24) * selectedPercent));
                canvas.drawText(mTitleProvider.getPageTitle(i).toString(), bound.left,
                        bound.bottom + mTopPadding, mPaintText);
            }
        }
    }

    // 
    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: {

        float TriangleLetf = curPageBound.left + +(curPageBound.right - curPageBound.left) / 2;
        TriangleLetf += mOffset;
        mPath = new Path();
        mPath.moveTo(TriangleLetf, height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(TriangleLetf + mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.lineTo(TriangleLetf - mFooterIndicatorHeight, height - mFooterLineHeight);
        mPath.close();
        mPaintFooterIndicator.setAlpha((int) (0xFF * selectedPercent));
        canvas.drawPath(mPath, mPaintFooterIndicator);
        mPaintFooterIndicator.setAlpha(0xFF);
        break;
    }
    case Underline: {
        int index = (int) (curPageBound.left / unitWidth);
        final float TriangleLetf = unitWidth * index + mOffset + mFooterIndicatorUnderlinePadding;
        final float TriangleRight = unitWidth * index + mOffset + unitWidth - mFooterIndicatorUnderlinePadding;
        mPath = new Path();
        mPath.moveTo(TriangleLetf, height - mFooterLineHeight);
        mPath.lineTo(TriangleRight, height - mFooterLineHeight);
        mPath.lineTo(TriangleRight, height - mFooterLineHeight - mFooterIndicatorHeight);
        mPath.lineTo(TriangleLetf, 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());/*www. j a  va 2  s  . c o m*/
    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);
    }
}

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

@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
    paint.setColor(getColor());//from w  w w  .j ava2 s .  c o m
    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(false);
        minY = graphView.getSecondScale().getMinY(false);
    } 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);
    }
}

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/*  w  ww  .  j ava 2  s.c  o m*/
 * @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:nu.yona.app.customview.graph.SpreadGraph.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.mCanvas = canvas;
    float fullWidth = canvas.getWidth();

    float heightOfbar = GraphUtils.convertSizeToDeviceDependent(mContext, graphHeight);
    //first bar/*  w  w w .j  a v a  2  s . com*/
    float mXStart = 0, mYStart = heightOfbar; // basically (X1, Y1)

    float bottom = heightOfbar; // height (distance from Y1 to Y2)

    mStartPoint = 0;
    mMiddlePoint = (fullWidth / 2);

    float spreadtime = fullWidth;

    float mPartSize = spreadtime / mNoParts;

    //todraw text from height
    float heightDraw = bottom + (GraphUtils.MARGIN_TOP * scaleFactor);

    //draw graphics of sun and moon
    Bitmap moonBitmap = drawableToBitmap(ContextCompat.getDrawable(mContext, R.drawable.icon_moon));
    float bitmapWidth = moonBitmap.getWidth() / 2;
    mCanvas.drawBitmap(moonBitmap, mStartPoint - (5 * scaleFactor), bottom + (5 * scaleFactor), null);
    mCanvas.drawBitmap(drawableToBitmap(ContextCompat.getDrawable(mContext, R.drawable.icn_sun)),
            mMiddlePoint - bitmapWidth, bottom + (5 * scaleFactor), null);

    float textPoint = (mMiddlePoint / 2) / 2;
    mCanvas.drawText(mContext.getString(R.string.four_hours), textPoint, heightDraw + scaleFactor,
            getFontStyle());
    float textPoint2 = textPoint * 2 + ((textPoint / 2));
    mCanvas.drawText(mContext.getString(R.string.eight_hours), textPoint2, heightDraw + scaleFactor,
            getFontStyle());
    float textPoint3 = textPoint * 5;
    mCanvas.drawText(mContext.getString(R.string.sixteen_hours), textPoint3 - bitmapWidth,
            heightDraw + scaleFactor, getFontStyle());
    float textPoint4 = textPoint * 6 + ((textPoint / 2));
    mCanvas.drawText(mContext.getString(R.string.twenty_hours), textPoint4 - bitmapWidth,
            heightDraw + scaleFactor, getFontStyle());
    float textPoint5 = textPoint * 7 + ((textPoint / 2));
    mCanvas.drawBitmap(drawableToBitmap(ContextCompat.getDrawable(mContext, R.drawable.icon_moon)), textPoint5,
            bottom + (5 * scaleFactor), null);

    if (mListZoneSpread != null && mListZoneSpread.size() > 0) {
        float currentStartPos;
        float currentEndPos;
        Paint barGraphPaint = new Paint();
        barGraphPaint.setStyle(Paint.Style.STROKE);
        barGraphPaint.setStrokeWidth(5);
        boolean skipThis;
        for (TimeZoneSpread timeZoneSpread : mListZoneSpread) {
            skipThis = false;
            currentStartPos = (float) timeZoneSpread.getIndex() * mPartSize;
            Path barPath = new Path();
            if (timeZoneSpread.getColor() == GraphUtils.COLOR_PINK
                    || timeZoneSpread.getColor() == GraphUtils.COLOR_BLUE) {
                currentEndPos = timeZoneSpread.getUsedValue();
                barGraphPaint.setColor(timeZoneSpread.getColor());
            } else if (timeZoneSpread.getColor() == GraphUtils.COLOR_GREEN) {
                if (timeZoneSpread.getUsedValue() == 15) {
                    currentEndPos = startEndPoint;
                    barGraphPaint.setColor(GraphUtils.COLOR_BULLET_DOT);
                } else {
                    currentEndPos = startEndPoint;
                    barGraphPaint.setColor(GraphUtils.COLOR_BLUE);
                }
            } else if (timeZoneSpread.getUsedValue() != 15
                    && timeZoneSpread.getColor() == GraphUtils.COLOR_BULLET_LIGHT_DOT) {
                currentEndPos = startEndPoint;
                barGraphPaint.setColor(timeZoneSpread.getColor());
                skipThis = true;
            } else {
                currentEndPos = startEndPoint;
                barGraphPaint.setColor(timeZoneSpread.getColor());
            }
            if (!skipThis) {
                float newXPos = mXStart + currentStartPos;
                barPath.moveTo(newXPos + 2, mYStart);
                float noPartsHeight = heightOfbar / 15;
                barPath.lineTo(currentStartPos + 2, mYStart - (currentEndPos * noPartsHeight) - 1);
                canvas.drawPath(barPath, barGraphPaint);
            }
        }

    }

}

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

public void onDraw(Canvas canvas) {
    if (mIsCropping) {
        boolean cropStartOnChart = isXScreenPointInChart(mCropStartData.screenPoint);
        boolean cropEndOnChart = isXScreenPointInChart(mCropEndData.screenPoint);

        // Draw grey overlays first, behind everything
        if (cropStartOnChart) {
            canvas.drawRect(mChartMarginLeft, mHeight - mChartHeight - mPaddingBottom,
                    mCropStartData.screenPoint.x, mHeight, mCropBackgroundPaint);
            // We can handle crop seekbar visibility in onDraw because the Seekbar Group is
            // in charge of receiving touch events, and that is always visible during cropping.
            mCropSeekbarGroup.getStartSeekBar().showThumb();
        } else {/*from w  ww . j ava 2  s.co  m*/
            mCropSeekbarGroup.getStartSeekBar().hideThumb();
        }
        if (cropEndOnChart) {
            canvas.drawRect(mCropEndData.screenPoint.x, mHeight - mChartHeight - mPaddingBottom,
                    mWidth - mChartMarginRight, mHeight, mCropBackgroundPaint);
            mCropSeekbarGroup.getEndSeekBar().showThumb();
        } else {
            mCropSeekbarGroup.getEndSeekBar().hideThumb();
        }

        // Draw the flags themselves
        if (cropStartOnChart) {
            // Drawing the start flag sets mFlagMeasurements to have the start flag's bounding
            // box. This will allow us to place the end flag appropriately.
            drawFlag(canvas, mCropStartData, mFlagMeasurements, true);
        } else {
            // Clear flag measurements when the left hand flag is offscreen, so that
            // drawFlagAfter does not see another flag to avoid.
            // This means pushing the expected previous flag measurements, stored in
            // mFlagMeasurements, off screen by at least the amount of the flag buffer, which
            // allows the next flag to start drawing at 0.
            // In drawFlagAfter we will use mFlagMeasurements.boxEnd to determine what to
            // avoid.
            mFlagMeasurements.boxEnd = -mCropFlagBufferX;
            mCropStartData.labelRect.set(OFFSCREEN, OFFSCREEN, OFFSCREEN, OFFSCREEN);
        }
        if (cropEndOnChart) {
            drawFlagAfter(canvas, mCropEndData, mFlagMeasurements, mFlagMeasurements.boxEnd, true);
        } else {
            mCropEndData.labelRect.set(OFFSCREEN, OFFSCREEN, OFFSCREEN, OFFSCREEN);
        }

        // Neither flag can be drawn, but we might be in a region that can be cropped out
        // so the whole thing should be colored grey.
        if (!cropEndOnChart && !cropStartOnChart) {
            if (mCropStartData.timestamp > mExternalAxis.mXMax
                    || mCropEndData.timestamp < mExternalAxis.mXMin) {
                canvas.drawRect(mChartMarginLeft, mHeight - mChartHeight - mPaddingBottom,
                        mWidth - mChartMarginRight, mHeight, mCropBackgroundPaint);
            }
        }
    } else {
        boolean xOnChart = isXScreenPointInChart(mPointData.screenPoint);
        boolean yOnChart = isYScreenPointInChart(mPointData.screenPoint);
        if (xOnChart && yOnChart) {
            // We are not cropping. Draw a standard flag.
            drawFlag(canvas, mPointData, mFlagMeasurements, false);

            // Draw the vertical line from the point to the bottom of the flag
            float nudge = mDotRadius / 2;
            float cy = mHeight - mChartHeight - mPaddingBottom + mPointData.screenPoint.y
                    - 2 * mDotBackgroundRadius + nudge;
            mPath.reset();
            mPath.moveTo(mPointData.screenPoint.x, mFlagMeasurements.notchBottom);
            mPath.lineTo(mPointData.screenPoint.x, cy);
            canvas.drawPath(mPath, mLinePaint);

            // Draw the selected point
            float cySmall = cy + 1.5f * mDotBackgroundRadius;
            canvas.drawCircle(mPointData.screenPoint.x, cySmall, mDotBackgroundRadius, mDotBackgroundPaint);
            canvas.drawCircle(mPointData.screenPoint.x, cySmall, mDotRadius, mDotPaint);
        } else {
            mPointData.labelRect.set(OFFSCREEN, OFFSCREEN, OFFSCREEN, OFFSCREEN);
        }
    }
}

From source file:com.hippo.widget.lockpattern.LockPatternView.java

@Override
protected void onDraw(Canvas canvas) {
    final ArrayList<Cell> pattern = mPattern;
    final int count = pattern.size();
    final boolean[][] drawLookup = mPatternDrawLookup;

    if (mPatternDisplayMode == DisplayMode.Animate) {

        // figure out which circles to draw

        // + 1 so we pause on complete pattern
        final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING;
        final int spotInCycle = (int) (SystemClock.elapsedRealtime() - mAnimatingPeriodStart) % oneCycle;
        final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING;

        clearPatternDrawLookup();/*  ww  w . ja  va2 s.co  m*/
        for (int i = 0; i < numCircles; i++) {
            final Cell cell = pattern.get(i);
            drawLookup[cell.getRow()][cell.getColumn()] = true;
        }

        // figure out in progress portion of ghosting line

        final boolean needToUpdateInProgressPoint = numCircles > 0 && numCircles < count;

        if (needToUpdateInProgressPoint) {
            final float percentageOfNextCircle = ((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING))
                    / MILLIS_PER_CIRCLE_ANIMATING;

            final Cell currentCell = pattern.get(numCircles - 1);
            final float centerX = getCenterXForColumn(currentCell.column);
            final float centerY = getCenterYForRow(currentCell.row);

            final Cell nextCell = pattern.get(numCircles);
            final float dx = percentageOfNextCircle * (getCenterXForColumn(nextCell.column) - centerX);
            final float dy = percentageOfNextCircle * (getCenterYForRow(nextCell.row) - centerY);
            mInProgressX = centerX + dx;
            mInProgressY = centerY + dy;
        }
        // TODO: Infinite loop here...
        invalidate();
    }

    final Path currentPath = mCurrentPath;
    currentPath.rewind();

    // draw the circles
    for (int i = 0; i < 3; i++) {
        float centerY = getCenterYForRow(i);
        for (int j = 0; j < 3; j++) {
            CellState cellState = mCellStates[i][j];
            float centerX = getCenterXForColumn(j);
            float size = cellState.size * cellState.scale;
            float translationY = cellState.translateY;
            drawCircle(canvas, (int) centerX, (int) centerY + translationY, size, drawLookup[i][j],
                    cellState.alpha);
        }
    }

    // TODO: the path should be created and cached every time we hit-detect a cell
    // only the last segment of the path should be computed here
    // draw the path of the pattern (unless we are in stealth mode)
    final boolean drawPath = !mInStealthMode;

    if (drawPath) {
        mPathPaint.setColor(getCurrentColor(true /* partOfPattern */));

        boolean anyCircles = false;
        float lastX = 0f;
        float lastY = 0f;
        for (int i = 0; i < count; i++) {
            Cell cell = pattern.get(i);

            // only draw the part of the pattern stored in
            // the lookup table (this is only different in the case
            // of animation).
            if (!drawLookup[cell.row][cell.column]) {
                break;
            }
            anyCircles = true;

            float centerX = getCenterXForColumn(cell.column);
            float centerY = getCenterYForRow(cell.row);
            if (i != 0) {
                CellState state = mCellStates[cell.row][cell.column];
                currentPath.rewind();
                currentPath.moveTo(lastX, lastY);
                if (state.lineEndX != Float.MIN_VALUE && state.lineEndY != Float.MIN_VALUE) {
                    currentPath.lineTo(state.lineEndX, state.lineEndY);
                } else {
                    currentPath.lineTo(centerX, centerY);
                }
                canvas.drawPath(currentPath, mPathPaint);
            }
            lastX = centerX;
            lastY = centerY;
        }

        // draw last in progress section
        if ((mPatternInProgress || mPatternDisplayMode == DisplayMode.Animate) && anyCircles) {
            currentPath.rewind();
            currentPath.moveTo(lastX, lastY);
            currentPath.lineTo(mInProgressX, mInProgressY);

            mPathPaint.setAlpha(
                    (int) (calculateLastSegmentAlpha(mInProgressX, mInProgressY, lastX, lastY) * 255f));
            canvas.drawPath(currentPath, mPathPaint);
        }
    }
}

From source file:net.droidsolutions.droidcharts.core.renderer.category.LineAndShapeRenderer.java

/**
 * Draw a single data item./*from   w w w  . j  a v a  2s. c o m*/
 * 
 * @param g2
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param dataArea
 *            the area in which the data is drawn.
 * @param plot
 *            the plot.
 * @param domainAxis
 *            the domain axis.
 * @param rangeAxis
 *            the range axis.
 * @param dataset
 *            the dataset.
 * @param row
 *            the row index (zero-based).
 * @param column
 *            the column index (zero-based).
 * @param pass
 *            the pass index.
 */
public void drawItem(Canvas g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,
        CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) {

    // do nothing if item is not visible
    if (!getItemVisible(row, column)) {
        return;
    }

    // do nothing if both the line and shape are not visible
    if (!getItemLineVisible(row, column) && !getItemShapeVisible(row, column)) {
        return;
    }

    // nothing is drawn for null...
    Number v = dataset.getValue(row, column);
    if (v == null) {
        return;
    }

    int visibleRow = state.getVisibleSeriesIndex(row);
    if (visibleRow < 0) {
        return;
    }
    int visibleRowCount = state.getVisibleSeriesCount();

    PlotOrientation orientation = plot.getOrientation();

    // current data point...
    double x1;
    if (this.useSeriesOffset) {
        x1 = domainAxis.getCategorySeriesMiddle(column, dataset.getColumnCount(), visibleRow, visibleRowCount,
                this.itemMargin, dataArea, plot.getDomainAxisEdge());
    } else {
        x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge());
    }
    double value = v.doubleValue();
    double y1 = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());

    if (pass == 0 && getItemLineVisible(row, column)) {
        if (column != 0) {
            Number previousValue = dataset.getValue(row, column - 1);
            if (previousValue != null) {
                // previous data point...
                double previous = previousValue.doubleValue();
                double x0;
                if (this.useSeriesOffset) {
                    x0 = domainAxis.getCategorySeriesMiddle(column - 1, dataset.getColumnCount(), visibleRow,
                            visibleRowCount, this.itemMargin, dataArea, plot.getDomainAxisEdge());
                } else {
                    x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea,
                            plot.getDomainAxisEdge());
                }
                double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge());

                Line2D line = null;
                if (orientation == PlotOrientation.HORIZONTAL) {
                    line = new Line2D.Double(y0, x0, y1, x1);
                } else if (orientation == PlotOrientation.VERTICAL) {
                    line = new Line2D.Double(x0, y0, x1, y1);
                }
                Paint paint = getItemPaint(row, column);
                Float stroke = getItemStroke(row, column);

                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(stroke);
                paint.setStrokeCap(Paint.Cap.ROUND);
                g2.drawLine((float) line.getX1(), (float) line.getY1(), (float) line.getX2(),
                        (float) line.getY2(), paint);
            }
        }
    }

    if (pass == 1) {
        Shape shape = getItemShape(row, column);
        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, y1, x1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, x1, y1);
        }

        if (getItemShapeVisible(row, column)) {
            if (getItemShapeFilled(row, column)) {
                Paint paint;
                if (this.useFillPaint) {
                    paint = getItemFillPaint(row, column);
                } else {
                    paint = getItemPaint(row, column);
                }
                paint.setStyle(Paint.Style.FILL_AND_STROKE);
                Path path = convertAwtPathToAndroid(shape.getPathIterator(null));
                g2.drawPath(path, paint);

            }
            if (this.drawOutlines) {
                Paint paint;
                if (this.useOutlinePaint) {
                    paint = getItemOutlinePaint(row, column);
                } else {
                    paint = getItemPaint(row, column);
                }
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(getItemOutlineStroke(row, column));
                Path path = convertAwtPathToAndroid(shape.getPathIterator(null));
                g2.drawPath(path, paint);
            }
        }

        // draw the item label if there is one...
        if (isItemLabelVisible(row, column)) {
            if (orientation == PlotOrientation.HORIZONTAL) {
                drawItemLabel(g2, orientation, dataset, row, column, y1, x1, (value < 0.0));
            } else if (orientation == PlotOrientation.VERTICAL) {
                drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value < 0.0));
            }
        }

        // submit the current data point as a crosshair candidate
        int datasetIndex = plot.indexOf(dataset);
        updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column),
                value, datasetIndex, x1, y1, orientation);

        // add an item entity, if this information is being collected
        EntityCollection entities = state.getEntityCollection();
        if (entities != null) {
            addItemEntity(entities, dataset, row, column, shape);
        }
    }

}