List of usage examples for android.graphics Canvas drawText
public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint)
From source file:com.bizcom.vc.widget.cus.SubsamplingScaleImageView.java
/** * Draw method should not be called until the view has dimensions so the * first calls are used as triggers to calculate the scaling and tiling * required. Once the view is setup, tiles are displayed as they are loaded. *//*from w w w . j av a2 s .co m*/ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); createPaints(); // If image or view dimensions are not known yet, abort. if (sWidth == 0 || sHeight == 0 || decoder == null || getWidth() == 0 || getHeight() == 0) { return; } // On first render with no tile map ready, initialise it and kick off // async base image loading. if (tileMap == null) { initialiseBaseLayer(getMaxBitmapDimensions(canvas)); return; } // If waiting to translate to new center position, set translate now if (sPendingCenter != null && pendingScale != null) { scale = pendingScale; vTranslate.x = (getWidth() / 2) - (scale * sPendingCenter.x); vTranslate.y = (getHeight() / 2) - (scale * sPendingCenter.y); sPendingCenter = null; pendingScale = null; fitToBounds(true); refreshRequiredTiles(true); } // On first display of base image set up position, and in other cases // make sure scale is correct. fitToBounds(false); // Everything is set up and coordinates are valid. Inform subclasses. if (!readySent) { readySent = true; new Thread(new Runnable() { public void run() { onImageReady(); } }).start(); } // If animating scale, calculate current scale and center with easing // equations if (anim != null) { long scaleElapsed = System.currentTimeMillis() - anim.time; boolean finished = scaleElapsed > anim.duration; scaleElapsed = Math.min(scaleElapsed, anim.duration); scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration); // Apply required animation to the focal point float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration); float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration); // Find out where the focal point is at this scale and adjust its // position to follow the animation path PointF vFocus = sourceToViewCoord(anim.sCenterEnd); vTranslate.x -= vFocus.x - vFocusNowX; vTranslate.y -= vFocus.y - vFocusNowY; // For translate anims, showing the image non-centered is never // allowed, for scaling anims it is during the animation. fitToBounds(finished || (anim.scaleStart == anim.scaleEnd)); refreshRequiredTiles(finished); if (finished) { anim = null; } invalidate(); } // Optimum sample size for current scale int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize()); // First check for missing tiles - if there are any we need the base // layer underneath to avoid gaps boolean hasMissingTiles = false; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.visible && (tile.loading || tile.bitmap == null)) { hasMissingTiles = true; } } } } // Render all loaded tiles. LinkedHashMap used for bottom up rendering - // lower res tiles underneath. for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) { for (Tile tile : tileMapEntry.getValue()) { Rect vRect = convertRect(sourceToViewRect(tile.sRect)); if (!tile.loading && tile.bitmap != null) { canvas.drawBitmap(tile.bitmap, null, vRect, bitmapPaint); if (debug) { canvas.drawRect(vRect, debugPaint); } } else if (tile.loading && debug) { canvas.drawText("LOADING", vRect.left + 5, vRect.top + 35, debugPaint); } if (tile.visible && debug) { canvas.drawText( "ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, vRect.left + 5, vRect.top + 15, debugPaint); } } } } if (debug) { canvas.drawText("Scale: " + String.format("%.2f", scale), 5, 15, debugPaint); canvas.drawText( "Translate: " + String.format("%.2f", vTranslate.x) + ":" + String.format("%.2f", vTranslate.y), 5, 35, debugPaint); PointF center = getCenter(); canvas.drawText( "Source center: " + String.format("%.2f", center.x) + ":" + String.format("%.2f", center.y), 5, 55, debugPaint); if (anim != null) { PointF vCenterStart = sourceToViewCoord(anim.sCenterStart); PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested); PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd); canvas.drawCircle(vCenterStart.x, vCenterStart.y, 10, debugPaint); canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, 20, debugPaint); canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, 25, debugPaint); canvas.drawCircle(getWidth() / 2, getHeight() / 2, 30, debugPaint); } } }
From source file:com.andexert.calendarlistview.library.SimpleMonthView.java
protected void drawMonthNums(Canvas canvas) { int y = (mRowHeight + MINI_DAY_NUMBER_TEXT_SIZE) / 2 - DAY_SEPARATOR_WIDTH + MONTH_HEADER_SIZE; int paddingDay = (mWidth - 2 * mPadding) / (2 * mNumDays); int dayOffset = findDayOffset(); int day = 1;/* w w w. j ava 2s. c o m*/ String toDayRes = getResources().getString(R.string.today); while (day <= mNumCells) { boolean isShowTrain = true; int x = paddingDay * (1 + dayOffset * 2) + mPadding; if ((mMonth == mSelectedBeginMonth && mSelectedBeginDay == day && mSelectedBeginYear == mYear) || (mMonth == mSelectedLastMonth && mSelectedLastDay == day && mSelectedLastYear == mYear)) { if (mDrawRect) { RectF rectF = new RectF(x - DAY_SELECTED_CIRCLE_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_CIRCLE_SIZE, x + DAY_SELECTED_CIRCLE_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_CIRCLE_SIZE); canvas.drawRoundRect(rectF, 10.0f, 10.0f, mSelectedCirclePaint); } else { canvas.drawCircle(x, y - MINI_DAY_NUMBER_TEXT_SIZE / 3, DAY_SELECTED_CIRCLE_SIZE, mSelectedCirclePaint); } isShowTrain = false; } if (mHasToday && (mToday == day)) { mMonthNumPaint.setColor(mCurrentDayTextColor); } else { mMonthNumPaint.setColor(mDayNumColor); mMonthNumPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); } if ((mMonth == mSelectedBeginMonth && mSelectedBeginDay == day && mSelectedBeginYear == mYear) || (mMonth == mSelectedLastMonth && mSelectedLastDay == day && mSelectedLastYear == mYear)) mMonthNumPaint.setColor(mMonthTitleBGColor); if ((mSelectedBeginDay != -1 && mSelectedLastDay != -1 && mSelectedBeginYear == mSelectedLastYear && mSelectedBeginMonth == mSelectedLastMonth && mSelectedBeginDay == mSelectedLastDay && day == mSelectedBeginDay && mMonth == mSelectedBeginMonth && mYear == mSelectedBeginYear)) { mMonthNumPaint.setColor(mSelectedDaysColor); } //? if ((mSelectedBeginDay != -1 && mSelectedLastDay != -1 && mSelectedBeginYear == mSelectedLastYear && mSelectedBeginYear == mYear) && (((mMonth == mSelectedBeginMonth && mSelectedLastMonth == mSelectedBeginMonth) && ((mSelectedBeginDay < mSelectedLastDay && day > mSelectedBeginDay && day < mSelectedLastDay) || (mSelectedBeginDay > mSelectedLastDay && day < mSelectedBeginDay && day > mSelectedLastDay))) || ((mSelectedBeginMonth < mSelectedLastMonth && mMonth == mSelectedBeginMonth && day > mSelectedBeginDay) || (mSelectedBeginMonth < mSelectedLastMonth && mMonth == mSelectedLastMonth && day < mSelectedLastDay)) || ((mSelectedBeginMonth > mSelectedLastMonth && mMonth == mSelectedBeginMonth && day < mSelectedBeginDay) || (mSelectedBeginMonth > mSelectedLastMonth && mMonth == mSelectedLastMonth && day > mSelectedLastDay)))) { mMonthNumPaint.setColor(mSelectedDaysColor); } if ((mSelectedBeginDay != -1 && mSelectedLastDay != -1 && mSelectedBeginYear != mSelectedLastYear && ((mSelectedBeginYear == mYear && mMonth == mSelectedBeginMonth) || (mSelectedLastYear == mYear && mMonth == mSelectedLastMonth)) && (((mSelectedBeginMonth < mSelectedLastMonth && mMonth == mSelectedBeginMonth && day < mSelectedBeginDay) || (mSelectedBeginMonth < mSelectedLastMonth && mMonth == mSelectedLastMonth && day > mSelectedLastDay)) || ((mSelectedBeginMonth > mSelectedLastMonth && mMonth == mSelectedBeginMonth && day > mSelectedBeginDay) || (mSelectedBeginMonth > mSelectedLastMonth && mMonth == mSelectedLastMonth && day < mSelectedLastDay))))) { mMonthNumPaint.setColor(mSelectedDaysColor); } if ((mSelectedBeginDay != -1 && mSelectedLastDay != -1 && mSelectedBeginYear == mSelectedLastYear && mYear == mSelectedBeginYear) && ((mMonth > mSelectedBeginMonth && mMonth < mSelectedLastMonth && mSelectedBeginMonth < mSelectedLastMonth) || (mMonth < mSelectedBeginMonth && mMonth > mSelectedLastMonth && mSelectedBeginMonth > mSelectedLastMonth))) { mMonthNumPaint.setColor(mSelectedDaysColor); } if ((mSelectedBeginDay != -1 && mSelectedLastDay != -1 && mSelectedBeginYear != mSelectedLastYear) && ((mSelectedBeginYear < mSelectedLastYear && ((mMonth > mSelectedBeginMonth && mYear == mSelectedBeginYear) || (mMonth < mSelectedLastMonth && mYear == mSelectedLastYear))) || (mSelectedBeginYear > mSelectedLastYear && ((mMonth < mSelectedBeginMonth && mYear == mSelectedBeginYear) || (mMonth > mSelectedLastMonth && mYear == mSelectedLastYear))))) { mMonthNumPaint.setColor(mSelectedDaysColor); } if ((!isPrevDayEnabled && prevDay(day, today)) || nextDay(day)) { mMonthNumPaint.setColor(mPreviousDayColor); } if (mHasToday && (mToday == day)) { canvas.drawText(toDayRes, x, y, mMonthNumPaint); } else { canvas.drawText(String.format("%d", day), x, y, mMonthNumPaint); } dayOffset++; if (dayOffset == mNumDays) { dayOffset = 0; y += mRowHeight; } day++; } }
From source file:com.am.pagergradienttab.view.PagerGradientTabStrip.java
/** * //ww w.j a va 2 s . co m * * @param canvas */ private void drawTag(Canvas canvas) { // TODO if (mTagAdapter != null) { canvas.save(); float canvasOffset = 0; int x = getPaddingLeft(); int y = getPaddingTop(); float textTop = 0; mTextPaint.setColor(Color.WHITE); mTextPaint.setTextAlign(Align.LEFT); for (int position = 0; position < tabs.size(); position++) { canvas.translate(canvasOffset, 0); canvasOffset = itemWidth + intervalWidth; canvas.save(); if (mTagAdapter.isEnable(position)) { int textWidth; int textHeight; mTextPaint.setTextSize(mTagAdapter.getTextSize(position)); String tag = mTagAdapter.getTag(position) == null ? "" : mTagAdapter.getTag(position); textWidth = (int) Math.ceil(mTextPaint.measureText(tag)); FontMetrics fontMetrics = mTextPaint.getFontMetrics(); textHeight = (int) Math.ceil(fontMetrics.descent - fontMetrics.ascent); textTop = textHeight - (-fontMetrics.ascent - fontMetrics.descent + (fontMetrics.bottom - fontMetrics.descent) * density); textHeight += textTop; if ("".equals(tag)) { textHeight = 0; } final Drawable drawable = mTagAdapter.getBackground(position); int drawableWidth = drawable == null ? 0 : drawable.getMinimumWidth(); int drawableHeight = drawable == null ? 0 : drawable.getMinimumHeight(); float offsetX = Math.max(textWidth + mTagAdapter.getPaddingLeft(position) + mTagAdapter.getPaddingRight(position), drawableWidth); float offsetTextX = (offsetX - (textWidth + mTagAdapter.getPaddingLeft(position) + mTagAdapter.getPaddingRight(position))) * 0.5f; float offsetY = Math.max(textHeight + mTagAdapter.getPaddingBottom(position) + mTagAdapter.getPaddingTop(position), drawableHeight); float offsetTextY = (offsetY - (textHeight + mTagAdapter.getPaddingBottom(position) + mTagAdapter.getPaddingTop(position))) * 0.5f; mTextPaint.setTextSize(showTextScale ? textSize * (1 + magnification) : textSize); float myTextWidth = mTextPaint.measureText(tabs.get(position)); TagAlign ta = mTagAdapter.getTagAlign(position); switch (ta) { default: case LEFTTOP: canvas.translate(mTagAdapter.getMarginLeft(position), mTagAdapter.getMarginTop(position)); break; case LEFTCENTER: canvas.translate(mTagAdapter.getMarginLeft(position), (getHeight() - underLineHeight - offsetY) / 2); break; case LEFTBOTTOM: canvas.translate(mTagAdapter.getMarginLeft(position), getHeight() - offsetY - underLineHeight - mTagAdapter.getMarginBottom(position)); break; case RIGHTTOP: canvas.translate(itemWidth - offsetX - mTagAdapter.getMarginRight(position), mTagAdapter.getMarginTop(position)); break; case RIGHTCENTER: canvas.translate(itemWidth - offsetX - mTagAdapter.getMarginRight(position), (getHeight() - underLineHeight - offsetY) / 2); break; case RIGHTBOTTOM: canvas.translate(itemWidth - offsetX - mTagAdapter.getMarginRight(position), getHeight() - offsetY - underLineHeight - mTagAdapter.getMarginBottom(position)); break; case LEFTTOPTEXT: canvas.translate( (itemWidth - myTextWidth) / 2 - offsetX - mTagAdapter.getMarginRight(position), mTagAdapter.getMarginTop(position)); break; case LEFTCENTERTEXT: canvas.translate( (itemWidth - myTextWidth) / 2 - offsetX - mTagAdapter.getMarginRight(position), (getHeight() - underLineHeight - offsetY) / 2); break; case LEFTBOTTOMTEXT: canvas.translate( (itemWidth - myTextWidth) / 2 - offsetX - mTagAdapter.getMarginRight(position), getHeight() - offsetY - underLineHeight - mTagAdapter.getMarginBottom(position)); break; case RIGHTTOPTEXT: canvas.translate((itemWidth + myTextWidth) / 2 + mTagAdapter.getMarginLeft(position), mTagAdapter.getMarginTop(position)); break; case RIGHTCENTERTEXT: canvas.translate((itemWidth + myTextWidth) / 2 + mTagAdapter.getMarginLeft(position), (getHeight() - underLineHeight - offsetY) / 2); break; case RIGHTBOTTOMTEXT: canvas.translate((itemWidth + myTextWidth) / 2 + mTagAdapter.getMarginLeft(position), getHeight() - offsetY - underLineHeight - mTagAdapter.getMarginBottom(position)); break; } mTextPaint.setTextSize(mTagAdapter.getTextSize(position)); if (drawable != null) { drawable.setBounds(x, y, (int) (x + offsetX), (int) (y + offsetY)); drawable.draw(canvas); } canvas.drawText(tag, x + offsetTextX + mTagAdapter.getPaddingLeft(position), y + offsetY - textTop - offsetTextY - mTagAdapter.getPaddingTop(position), mTextPaint); } canvas.restore(); } canvas.restore(); } }
From source file:com.appeaser.sublimepickerlibrary.datepicker.SimpleMonthView.java
/** * Draws the month days.//from w ww . j a v a2 s.c o m */ @SuppressWarnings("ConstantConditions") private void drawDays(Canvas canvas) { final TextPaint p = mDayPaint; final int headerHeight = mMonthHeight + mDayOfWeekHeight; //final int rowHeight = mDayHeight; final float rowHeight = mDayHeight; //final int colWidth = mCellWidth; final float colWidth = mCellWidth; // Text is vertically centered within the row height. final float halfLineHeight = (p.ascent() + p.descent()) / 2f; //int rowCenter = headerHeight + rowHeight / 2; float rowCenter = headerHeight + rowHeight / 2f; for (int day = 1, col = findDayOffset(); day <= mDaysInMonth; day++) { //final int colCenter = colWidth * col + colWidth / 2; final float colCenter = colWidth * col + colWidth / 2f; //final int colCenterRtl; final float colCenterRtl; if (SUtils.isLayoutRtlCompat(this)) { colCenterRtl = mPaddedWidth - colCenter; } else { colCenterRtl = colCenter; } int stateMask = 0; final boolean isDayEnabled = isDayEnabled(day); if (isDayEnabled) { stateMask |= SUtils.STATE_ENABLED; } final boolean isDayInActivatedRange = mActivatedDays.isValid() && mActivatedDays.isActivated(day); final boolean isSelected = mActivatedDays.isSelected(day); if (isSelected) { stateMask |= SUtils.STATE_ACTIVATED; canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDaySelectorPaint); } else if (isDayInActivatedRange) { stateMask |= SUtils.STATE_ACTIVATED; int bgShape = DRAW_RECT; if (mActivatedDays.isSingleDay()) { if (mActivatedDays.isStartOfMonth()) { bgShape = DRAW_RECT_WITH_CURVE_ON_RIGHT; } else { bgShape = DRAW_RECT_WITH_CURVE_ON_LEFT; } } else if (mActivatedDays.isStartingDayOfRange(day)) { bgShape = DRAW_RECT_WITH_CURVE_ON_LEFT; } else if (mActivatedDays.isEndingDayOfRange(day)) { bgShape = DRAW_RECT_WITH_CURVE_ON_RIGHT; } // Use height to constrain the protrusion of the arc boolean constrainProtrusion = colWidth > (rowHeight - (2 * mPaddingRangeIndicator)); float horDistFromCenter = constrainProtrusion ? rowHeight / 2f - mPaddingRangeIndicator : colWidth / 2f; switch (bgShape) { case DRAW_RECT_WITH_CURVE_ON_LEFT: int leftRectArcLeft = (int) (colCenterRtl - horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl - horDistFromCenter) + 1 : (int) (colCenterRtl - horDistFromCenter); int leftRectArcRight = (int) (colCenterRtl + horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl + horDistFromCenter) + 1 : (int) (colCenterRtl + horDistFromCenter); RectF leftArcRect = new RectF(leftRectArcLeft, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, leftRectArcRight, rowCenter + rowHeight / 2f - mPaddingRangeIndicator); canvas.drawArc(leftArcRect, 90, 180, true, mDayRangeSelectorPaint); canvas.drawRect(new RectF(leftArcRect.centerX(), rowCenter - rowHeight / 2f + mPaddingRangeIndicator, colCenterRtl + colWidth / 2f, rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; case DRAW_RECT_WITH_CURVE_ON_RIGHT: int rightRectArcLeft = (int) (colCenterRtl - horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl - horDistFromCenter) + 1 : (int) (colCenterRtl - horDistFromCenter); int rightRectArcRight = (int) (colCenterRtl + horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl + horDistFromCenter) + 1 : (int) (colCenterRtl + horDistFromCenter); RectF rightArcRect = new RectF(rightRectArcLeft, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, rightRectArcRight, rowCenter + rowHeight / 2f - mPaddingRangeIndicator); canvas.drawArc(rightArcRect, 270, 180, true, mDayRangeSelectorPaint); canvas.drawRect(new RectF(colCenterRtl - colWidth / 2f, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, rightArcRect.centerX(), rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; default: canvas.drawRect(new RectF(colCenterRtl - colWidth / 2f, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, colCenterRtl + colWidth / 2f, rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; } } if (mTouchedItem == day) { stateMask |= SUtils.STATE_PRESSED; if (isDayEnabled) { canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDayHighlightPaint); } } final boolean isDayToday = mToday == day; final int dayTextColor; if (isDayToday && !isDayInActivatedRange) { dayTextColor = mDaySelectorPaint.getColor(); } else { final int[] stateSet = SUtils.resolveStateSet(stateMask); dayTextColor = mDayTextColor.getColorForState(stateSet, 0); } p.setColor(dayTextColor); canvas.drawText(mDayFormatter.format(day), colCenterRtl, rowCenter - halfLineHeight, p); col++; if (col == DAYS_IN_WEEK) { col = 0; rowCenter += rowHeight; } } }
From source file:devlight.io.library.ArcProgressStackView.java
@Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); // Save and rotate to start angle canvas.save();/*from w ww . j a va 2 s .c o m*/ final float radius = mSize * 0.5F; canvas.rotate(mStartAngle, radius, radius); // Draw all of progress for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); // Get progress for current model float progressFraction = mIsAnimated && !isInEditMode() ? (model.mLastProgress + (mAnimatedFraction * (model.getProgress() - model.mLastProgress))) / MAX_PROGRESS : model.getProgress() / MAX_PROGRESS; if (i != mActionMoveModelIndex && mActionMoveModelIndex != ANIMATE_ALL_INDEX) progressFraction = model.getProgress() / MAX_PROGRESS; final float progress = progressFraction * mSweepAngle; // Check if model have gradient final boolean isGradient = model.getColors() != null; // Set width of progress mProgressPaint.setStrokeWidth(mProgressModelSize); // Set model arc progress model.mPath.reset(); model.mPath.addArc(model.mBounds, 0.0F, progress); // Draw gradient progress or solid resetShadowLayer(); mProgressPaint.setShader(null); mProgressPaint.setStyle(Paint.Style.STROKE); if (mIsModelBgEnabled) { //noinspection ResourceAsColor mProgressPaint.setColor(isInEditMode() ? mPreviewModelBgColor : model.getBgColor()); canvas.drawArc(model.mBounds, 0.0F, mSweepAngle, false, mProgressPaint); if (!isInEditMode()) mProgressPaint.clearShadowLayer(); } // Check if gradient for draw shadow at first and then gradient progress if (isGradient) { if (!mIsModelBgEnabled) { canvas.drawPath(model.mPath, mProgressPaint); if (!isInEditMode()) mProgressPaint.clearShadowLayer(); } mProgressPaint.setShader(model.mSweepGradient); } else mProgressPaint.setColor(model.getColor()); // Here we draw main progress mProgressPaint.setAlpha(255); canvas.drawPath(model.mPath, mProgressPaint); // Preview mode if (isInEditMode()) continue; // Get model title bounds mTextPaint.setTextSize(mProgressModelSize * 0.5F); mTextPaint.getTextBounds(model.getTitle(), 0, model.getTitle().length(), model.mTextBounds); // Draw title at start with offset final float titleHorizontalOffset = model.mTextBounds.height() * 0.5F; final float progressLength = (float) (Math.PI / 180.0F) * progress * model.mBounds.width() * 0.5F; final String title = (String) TextUtils.ellipsize(model.getTitle(), mTextPaint, progressLength - titleHorizontalOffset * 2, TextUtils.TruncateAt.END); canvas.drawTextOnPath(title, model.mPath, mIsRounded ? 0.0F : titleHorizontalOffset, titleHorizontalOffset, mTextPaint); // Get pos and tan at final path point model.mPathMeasure.setPath(model.mPath, false); model.mPathMeasure.getPosTan(model.mPathMeasure.getLength(), model.mPos, model.mTan); // Get title width final float titleWidth = model.mTextBounds.width(); // Create model progress like : 23% final String percentProgress = String.format("%d%%", (int) model.getProgress()); // Get progress text bounds mTextPaint.setTextSize(mProgressModelSize * 0.35f); mTextPaint.getTextBounds(percentProgress, 0, percentProgress.length(), model.mTextBounds); // Get pos tan with end point offset and check whether the rounded corners for offset final float progressHorizontalOffset = mIndicatorOrientation == IndicatorOrientation.VERTICAL ? model.mTextBounds.height() * 0.5F : model.mTextBounds.width() * 0.5F; final float indicatorProgressOffset = (mIsRounded ? progressFraction : 1.0F) * (-progressHorizontalOffset - titleHorizontalOffset - (mIsRounded ? model.mTextBounds.height() * 2.0F : 0.0F)); model.mPathMeasure.getPosTan(model.mPathMeasure.getLength() + indicatorProgressOffset, model.mPos, mIndicatorOrientation == IndicatorOrientation.VERTICAL && !mIsRounded ? new float[2] : model.mTan); // Check if there available place for indicator if ((titleWidth + model.mTextBounds.height() + titleHorizontalOffset * 2.0F) - indicatorProgressOffset < progressLength) { // Get rotate indicator progress angle for progress value float indicatorProgressAngle = (float) (Math.atan2(model.mTan[1], model.mTan[0]) * (180.0F / Math.PI)); // Get arc angle of progress indicator final float indicatorLengthProgressAngle = ((progressLength + indicatorProgressOffset) / (model.mBounds.width() * 0.5F)) * (float) (180.0F / Math.PI); // Detect progress indicator position : left or right and then rotate if (mIndicatorOrientation == IndicatorOrientation.VERTICAL) { // Get X point of arc angle progress indicator final float x = (float) (model.mBounds.width() * 0.5F * (Math.cos((indicatorLengthProgressAngle + mStartAngle) * Math.PI / 180.0F))) + model.mBounds.centerX(); indicatorProgressAngle += (x > radius) ? -90.0F : 90.0F; } else { // Get Y point of arc angle progress indicator final float y = (float) (model.mBounds.height() * 0.5F * (Math.sin((indicatorLengthProgressAngle + mStartAngle) * Math.PI / 180.0F))) + model.mBounds.centerY(); indicatorProgressAngle += (y > radius) ? 180.0F : 0.0F; } // Draw progress value canvas.save(); canvas.rotate(indicatorProgressAngle, model.mPos[0], model.mPos[1]); canvas.drawText(percentProgress, model.mPos[0] - model.mTextBounds.exactCenterX(), model.mPos[1] - model.mTextBounds.exactCenterY(), mTextPaint); canvas.restore(); } // Check if gradient and have rounded corners, because we must to create elevation effect // for start progress corner if ((isGradient || mIsLeveled) && mIsRounded && progress != 0) { model.mPathMeasure.getPosTan(0.0F, model.mPos, model.mTan); // Set paint for overlay rounded gradient with shadow setLevelShadowLayer(); //noinspection ResourceAsColor mLevelPaint.setColor(isGradient ? model.getColors()[0] : model.getColor()); // Get bounds of start pump final float halfSize = mProgressModelSize * 0.5F; final RectF arcRect = new RectF(model.mPos[0] - halfSize, model.mPos[1] - halfSize, model.mPos[0] + halfSize, model.mPos[1] + halfSize + 2.0F); canvas.drawArc(arcRect, 0.0F, -180.0F, true, mLevelPaint); } } // Restore after drawing canvas.restore(); }
From source file:com.miuhouse.yourcompany.student.view.widget.date.datepicker.SimpleMonthView.java
/** * Draws the month days./* ww w . j a va 2 s. c o m*/ */ @SuppressWarnings("ConstantConditions") private void drawDays(Canvas canvas) { final TextPaint p = mDayPaint; final int headerHeight = mMonthHeight + mDayOfWeekHeight; final float rowHeight = mDayHeight; final float colWidth = mCellWidth; // Text is vertically centered within the row height. final float halfLineHeight = (p.ascent() + p.descent()) / 2f; // int rowCenter = headerHeight + rowHeight / 2; float rowCenter = headerHeight + rowHeight / 2f; //mDaysInMonth303129 for (int day = 1, col = findDayOffset(); day <= mDaysInMonth; day++) { final float colCenter = colWidth * col + colWidth / 2f; //final int colCenterRtl; final float colCenterRtl; if (SUtils.isLayoutRtlCompat(this)) { colCenterRtl = mPaddedWidth - colCenter; } else { colCenterRtl = colCenter; } int stateMask = 0; final boolean isDayEnabled = isDayEnabled(day); if (isDayEnabled) { stateMask |= SUtils.STATE_ENABLED; } final boolean isDayInActivatedRange = mActivatedDays.isValid() && mActivatedDays.isActivated(day); final boolean isSelected = mActivatedDays.isSelected(day); final boolean isSelectedAndTogether = mActivatedDays.isSelectedAndTogether(day); if (isSelectedAndTogether) { if ((!disable && !isDisable) || isFill) { stateMask |= SUtils.STATE_ACTIVATED; canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDaySelectorPaint); } } if (!isSelected && isDayInActivatedRange) { stateMask |= SUtils.STATE_ACTIVATED; int bgShape = DRAW_RECT; if (mActivatedDays.isSingleDay()) { if (mActivatedDays.isStartOfMonth()) { bgShape = DRAW_RECT_WITH_CURVE_ON_RIGHT; } else { bgShape = DRAW_RECT_WITH_CURVE_ON_LEFT; } } else if (mActivatedDays.isStartingDayOfRange(day)) { bgShape = DRAW_RECT_WITH_CURVE_ON_LEFT; } else if (mActivatedDays.isEndingDayOfRange(day)) { bgShape = DRAW_RECT_WITH_CURVE_ON_RIGHT; } // Use height to constrain the protrusion of the arc boolean constrainProtrusion = colWidth > (rowHeight - (2 * mPaddingRangeIndicator)); float horDistFromCenter = constrainProtrusion ? rowHeight / 2f - mPaddingRangeIndicator : colWidth / 2f; switch (bgShape) { case DRAW_RECT_WITH_CURVE_ON_LEFT: int leftRectArcLeft = (int) (colCenterRtl - horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl - horDistFromCenter) + 1 : (int) (colCenterRtl - horDistFromCenter); int leftRectArcRight = (int) (colCenterRtl + horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl + horDistFromCenter) + 1 : (int) (colCenterRtl + horDistFromCenter); RectF leftArcRect = new RectF(leftRectArcLeft, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, leftRectArcRight, rowCenter + rowHeight / 2f - mPaddingRangeIndicator); canvas.drawArc(leftArcRect, 90, 180, true, mDayRangeSelectorPaint); canvas.drawRect(new RectF(leftArcRect.centerX(), rowCenter - rowHeight / 2f + mPaddingRangeIndicator, colCenterRtl + colWidth / 2f, rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; case DRAW_RECT_WITH_CURVE_ON_RIGHT: int rightRectArcLeft = (int) (colCenterRtl - horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl - horDistFromCenter) + 1 : (int) (colCenterRtl - horDistFromCenter); int rightRectArcRight = (int) (colCenterRtl + horDistFromCenter) % 2 == 1 ? (int) (colCenterRtl + horDistFromCenter) + 1 : (int) (colCenterRtl + horDistFromCenter); RectF rightArcRect = new RectF(rightRectArcLeft, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, rightRectArcRight, rowCenter + rowHeight / 2f - mPaddingRangeIndicator); canvas.drawArc(rightArcRect, 270, 180, true, mDayRangeSelectorPaint); canvas.drawRect(new RectF(colCenterRtl - colWidth / 2f, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, rightArcRect.centerX(), rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; default: canvas.drawRect(new RectF(colCenterRtl - colWidth / 2f, rowCenter - rowHeight / 2f + mPaddingRangeIndicator, colCenterRtl + colWidth / 2f, rowCenter + rowHeight / 2f - mPaddingRangeIndicator), mDayRangeSelectorPaint); break; } } final boolean isDayToday = mToday == day; final int dayTextColor; if (isDayToday) { if (mActivatedDays.isClick && isSelected) { final int[] stateSet = SUtils.resolveStateSet(stateMask); dayTextColor = mDayTextColor.getColorForState(stateSet, 0); } else { dayTextColor = mDaySelectorPaint.getColor(); } } else { final int[] stateSet = SUtils.resolveStateSet(stateMask); if (!mActivatedDays.isSingleDay()) { if (stateMask == 1) { dayTextColor = mContext.getResources().getColor(R.color.textDarkfour); } else { dayTextColor = mDayTextColor.getColorForState(stateSet, 0); } } else { dayTextColor = mDayTextColor.getColorForState(stateSet, 0); } } p.setColor(dayTextColor); canvas.drawText(mDayFormatter.format(day), colCenterRtl, rowCenter - halfLineHeight, p); col++; if (col == DAYS_IN_WEEK) { col = 0; rowCenter += rowHeight; } if (mDaysInMonth == day) mOnRangeClickListener.onRangeSelected(calendars, position); } }
From source file:net.toload.main.hd.candidate.CandidateView.java
private void doDraw(Canvas canvas) { if (mSuggestions == null) return;/*from w w w .ja va 2 s . co m*/ if (DEBUG) Log.i(TAG, "CandidateView:doDraw():Suggestion mCount:" + mCount + " mSuggestions.size:" + mSuggestions.size()); mTotalWidth = 0; updateFontSize(); if (mBgPadding == null) { mBgPadding = new Rect(0, 0, 0, 0); if (getBackground() != null) { getBackground().getPadding(mBgPadding); } } final int height = mHeight; final Rect bgPadding = mBgPadding; final Paint candidatePaint = mCandidatePaint; final Paint candidateEmojiPaint = mCandidatePaint; candidateEmojiPaint.setTextSize((float) (candidateEmojiPaint.getTextSize() * 0.9)); final Paint selKeyPaint = mSelKeyPaint; final int touchX = mTouchX; final int scrollX = getScrollX(); final boolean scrolled = mScrolled; final int textBaseLine = (int) (((height - mCandidatePaint.getTextSize()) / 2) - mCandidatePaint.ascent()); // Modified by jeremy '10, 3, 29. Update mselectedindex if touched and build wordX[i] and wordwidth[i] int x = 0; final int count = mCount; //Cache count here '11,8,18 for (int i = 0; i < count; i++) { if (count != mCount || mSuggestions == null || count != mSuggestions.size() || mSuggestions.size() == 0 || i >= mSuggestions.size()) return; // mSuggestion is updated, force abort String suggestion = mSuggestions.get(i).getWord(); if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord() && suggestion.length() > 8) { suggestion = suggestion.substring(0, 2) + ".."; } float base = (suggestion == null) ? 0 : candidatePaint.measureText(""); float textWidth = (suggestion == null) ? 0 : candidatePaint.measureText(suggestion); if (textWidth < base) { textWidth = base; } final int wordWidth = (int) textWidth + X_GAP * 2; mWordX[i] = x; mWordWidth[i] = wordWidth; if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) { mSelectedIndex = i; } x += wordWidth; } mTotalWidth = x; if (DEBUG) Log.i(TAG, "CandidateView:doDraw():mTotalWidth :" + mTotalWidth + " this.getWidth():" + this.getWidth()); //Jeremy '11,8,11. If the candidate list is within 1 page and has more records, get full records first. if (mTotalWidth < this.getWidth()) checkHasMoreRecords(); // Paint all the suggestions and lines. if (canvas != null) { // Moved from above by jeremy '10 3, 29. Paint mSelectedindex in highlight here if (count > 0 && mSelectedIndex >= 0) { // candidatePaint.setColor(mColorComposingCode); // canvas.drawRect(mWordX[mSelectedIndex],bgPadding.top, mWordWidth[mSelectedIndex] , height, candidatePaint); canvas.translate(mWordX[mSelectedIndex], 0); mDrawableSuggestHighlight.setBounds(0, bgPadding.top, mWordWidth[mSelectedIndex], height); mDrawableSuggestHighlight.draw(canvas); canvas.translate(-mWordX[mSelectedIndex], 0); } if (mTransparentCandidateView) { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); Paint backgroundPaint = new Paint(); backgroundPaint.setColor(ContextCompat.getColor(mContext, R.color.third_background_light)); backgroundPaint.setAlpha(33); backgroundPaint.setStyle(Paint.Style.FILL); canvas.drawRect(0.5f, bgPadding.top, mScreenWidth, height, backgroundPaint); } for (int i = 0; i < count; i++) { if (count != mCount || mSuggestions == null || count != mSuggestions.size() || mSuggestions.size() == 0 || i >= mSuggestions.size()) break; boolean isEmoji = mSuggestions.get(i).isEmojiRecord(); String suggestion = mSuggestions.get(i).getWord(); if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord() && suggestion.length() > 8) { suggestion = suggestion.substring(0, 2) + ".."; } int c = i + 1; switch (mSuggestions.get(i).getRecordType()) { case Mapping.RECORD_COMPOSING_CODE: if (mSelectedIndex == 0) { if (mTransparentCandidateView) { candidatePaint.setColor(mColorInvertedTextTransparent); } else { candidatePaint.setColor(mColorComposingCodeHighlight); } } else candidatePaint.setColor(mColorComposingCode); break; case Mapping.RECORD_CHINESE_PUNCTUATION_SYMBOL: case Mapping.RECORD_RELATED_PHRASE: selKeyPaint.setColor(mColorSelKeyShifted); if (i == mSelectedIndex) candidatePaint.setColor(mColorNormalTextHighlight); else candidatePaint.setColor(mColorNormalText); break; case Mapping.RECORD_EXACT_MATCH_TO_CODE: case Mapping.RECORD_PARTIAL_MATCH_TO_CODE: case Mapping.RECORD_RUNTIME_BUILT_PHRASE: case Mapping.RECORD_ENGLISH_SUGGESTION: default: selKeyPaint.setColor(mColorSelKey); if (i == mSelectedIndex) candidatePaint.setColor(mColorNormalTextHighlight); else candidatePaint.setColor(mColorNormalText); break; } if (isEmoji) { canvas.drawText(suggestion, mWordX[i] + X_GAP, Math.round(textBaseLine * 0.95), candidateEmojiPaint); } else { canvas.drawText(suggestion, mWordX[i] + X_GAP, textBaseLine, candidatePaint); } if (mShowNumber) { //Jeremy '11,6,17 changed from <=10 to mDisplaySelkey length. The length maybe 11 or 12 if shifted with space. if (c <= mDisplaySelkey.length()) { //Jeremy '11,6,11 Drawing text using relative font dimensions. canvas.drawText(mDisplaySelkey.substring(c - 1, c), mWordX[i] + mWordWidth[i] - height * 0.3f, height * 0.4f, selKeyPaint); } } //Draw spacer candidatePaint.setColor(mColorSpacer); canvas.drawLine(mWordX[i] + mWordWidth[i] + 0.5f, bgPadding.top + (mVerticalPadding / 2), mWordX[i] + mWordWidth[i] + 0.5f, height - (mVerticalPadding / 2), candidatePaint); candidatePaint.setFakeBoldText(false); } if (mTargetScrollX != getScrollX()) { if (DEBUG) Log.i(TAG, "CandidateView:doDraw():mTargetScrollX :" + mTargetScrollX + " getScrollX():" + getScrollX()); scrollToTarget(); } } }
From source file:p5e610.graphview.series.BarGraphSeries.java
/** * draws the bars on the canvas/*w w w . j a v a2 s . co m*/ * * @param graphView corresponding graphview * @param canvas canvas * @param isSecondScale whether we are plotting the second scale or not */ @Override public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) { mPaint.setTextAlign(Paint.Align.CENTER); if (mValuesOnTopSize == 0) { mValuesOnTopSize = graphView.getGridLabelRenderer().getTextSize(); } mPaint.setTextSize(mValuesOnTopSize); 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); } // Iterate through all bar graph series // so we know how wide to make our bar, // and in what position to put it in int numBarSeries = 0; int currentSeriesOrder = 0; int numValues = 0; boolean isCurrentSeries; SortedSet<Double> xVals = new TreeSet<Double>(); for (Series inspectedSeries : graphView.getSeries()) { if (inspectedSeries instanceof BarGraphSeries) { isCurrentSeries = (inspectedSeries == this); if (isCurrentSeries) { currentSeriesOrder = numBarSeries; } numBarSeries++; // calculate the number of slots for bars based on the minimum distance between // x coordinates in the series. This is divided into the range to find // the placement and width of bar slots // (sections of the x axis for each bar or set of bars) Iterator<E> curValues = inspectedSeries.getValues(minX, maxX); if (curValues.hasNext()) { xVals.add(curValues.next().getX()); if (isCurrentSeries) { numValues++; } while (curValues.hasNext()) { xVals.add(curValues.next().getX()); if (isCurrentSeries) { numValues++; } } } } } if (numValues == 0) { return; } double minGap = 0; if (mDataWidth > 0.0) { minGap = mDataWidth; } else { Double lastVal = null; for (Double curVal : xVals) { if (lastVal != null) { double curGap = Math.abs(curVal - lastVal); if (minGap == 0 || (curGap > 0 && curGap < minGap)) { minGap = curGap; } } lastVal = curVal; } } int numBarSlots = (minGap == 0) ? 1 : (int) Math.round((maxX - minX) / minGap) + 1; Iterator<E> values = getValues(minX, maxX); // Calculate the overall bar slot width - this includes all bars across // all series, and any spacing between sets of bars int barSlotWidth = numBarSlots == 1 ? graphView.getGraphContentWidth() : graphView.getGraphContentWidth() / (numBarSlots - 1); // Total spacing (both sides) between sets of bars double spacing = Math.min(barSlotWidth * mSpacing / 100, barSlotWidth * 0.98f); // Width of an individual bar double barWidth = (barSlotWidth - spacing) / numBarSeries; // Offset from the center of a given bar to start drawing double offset = barSlotWidth / 2; double diffY = maxY - minY; double diffX = maxX - minX; double contentHeight = graphView.getGraphContentHeight(); double contentWidth = graphView.getGraphContentWidth(); double contentLeft = graphView.getGraphContentLeft(); double contentTop = graphView.getGraphContentTop(); // draw data int i = 0; while (values.hasNext()) { E value = values.next(); double valY = value.getY() - minY; double ratY = valY / diffY; double y = contentHeight * ratY; double valY0 = 0 - minY; double ratY0 = valY0 / diffY; double y0 = contentHeight * ratY0; double valueX = value.getX(); double valX = valueX - minX; double ratX = valX / diffX; double x = contentWidth * ratX; // hook for value dependent color if (getValueDependentColor() != null) { mPaint.setColor(getValueDependentColor().get(value)); } else { mPaint.setColor(getColor()); } double left = x + contentLeft - offset + spacing / 2 + currentSeriesOrder * barWidth; double top = (contentTop - y) + contentHeight; double right = left + barWidth; double bottom = (contentTop - y0) + contentHeight - (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1); boolean reverse = top > bottom; if (mAnimated) { if ((Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) { long currentTime = System.currentTimeMillis(); if (mAnimationStart == 0) { // start animation mAnimationStart = currentTime; mAnimationStartFrameNo = 0; } else { // anti-lag: wait a few frames if (mAnimationStartFrameNo < 15) { // second time mAnimationStart = currentTime; mAnimationStartFrameNo++; } } float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION; float factor = mAnimationInterpolator.getInterpolation(timeFactor); if (timeFactor <= 1.0) { double barHeight = bottom - top; barHeight = barHeight * factor; top = bottom - barHeight; ViewCompat.postInvalidateOnAnimation(graphView); } else { // animation finished mLastAnimatedValue = valueX; } } } if (reverse) { double tmp = top; top = bottom + (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1); bottom = tmp; } // overdraw left = Math.max(left, contentLeft); right = Math.min(right, contentLeft + contentWidth); bottom = Math.min(bottom, contentTop + contentHeight); top = Math.max(top, contentTop); mDataPoints.put(new RectD(left, top, right, bottom), value); Paint p; if (mCustomPaint != null) { p = mCustomPaint; } else { p = mPaint; } canvas.drawRect((float) left, (float) top, (float) right, (float) bottom, p); // set values on top of graph if (mDrawValuesOnTop) { if (reverse) { top = bottom + mValuesOnTopSize + 4; if (top > contentTop + contentHeight) top = contentTop + contentHeight; } else { top -= 4; if (top <= contentTop) top += contentTop + 4; } mPaint.setColor(mValuesOnTopColor); canvas.drawText( graphView.getGridLabelRenderer().getLabelFormatter().formatLabel(value.getY(), false), (float) (left + right) / 2, (float) top, mPaint); } i++; } }
From source file:com.jjoe64.graphview.series.BarGraphSeries.java
/** * draws the bars on the canvas/*from ww w. j a v a 2s . c om*/ * * @param graphView corresponding graphview * @param canvas canvas * @param isSecondScale whether we are plotting the second scale or not */ @Override public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) { mPaint.setTextAlign(Paint.Align.CENTER); if (mValuesOnTopSize == 0) { mValuesOnTopSize = graphView.getGridLabelRenderer().getTextSize(); } mPaint.setTextSize(mValuesOnTopSize); 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); } // Iterate through all bar graph series // so we know how wide to make our bar, // and in what position to put it in int numBarSeries = 0; int currentSeriesOrder = 0; int numValues = 0; boolean isCurrentSeries; SortedSet<Double> xVals = new TreeSet<Double>(); for (Series inspectedSeries : graphView.getSeries()) { if (inspectedSeries instanceof BarGraphSeries) { isCurrentSeries = (inspectedSeries == this); if (isCurrentSeries) { currentSeriesOrder = numBarSeries; } numBarSeries++; // calculate the number of slots for bars based on the minimum distance between // x coordinates in the series. This is divided into the range to find // the placement and width of bar slots // (sections of the x axis for each bar or set of bars) // TODO: Move this somewhere more general and cache it, so we don't recalculate it for each series Iterator<E> curValues = inspectedSeries.getValues(minX, maxX); if (curValues.hasNext()) { xVals.add(curValues.next().getX()); if (isCurrentSeries) { numValues++; } while (curValues.hasNext()) { xVals.add(curValues.next().getX()); if (isCurrentSeries) { numValues++; } } } } } if (numValues == 0) { return; } double minGap = 0; if (mDataWidth > 0.0) { minGap = mDataWidth; } else { Double lastVal = null; for (Double curVal : xVals) { if (lastVal != null) { double curGap = Math.abs(curVal - lastVal); if (minGap == 0 || (curGap > 0 && curGap < minGap)) { minGap = curGap; } } lastVal = curVal; } } int numBarSlots = (minGap == 0) ? 1 : (int) Math.round((maxX - minX) / minGap) + 1; Iterator<E> values = getValues(minX, maxX); // Calculate the overall bar slot width - this includes all bars across // all series, and any spacing between sets of bars int barSlotWidth = numBarSlots == 1 ? graphView.getGraphContentWidth() : graphView.getGraphContentWidth() / (numBarSlots - 1); // Total spacing (both sides) between sets of bars double spacing = Math.min(barSlotWidth * mSpacing / 100, barSlotWidth * 0.98f); // Width of an individual bar double barWidth = (barSlotWidth - spacing) / numBarSeries; // Offset from the center of a given bar to start drawing double offset = barSlotWidth / 2; double diffY = maxY - minY; double diffX = maxX - minX; double contentHeight = graphView.getGraphContentHeight(); double contentWidth = graphView.getGraphContentWidth(); double contentLeft = graphView.getGraphContentLeft(); double contentTop = graphView.getGraphContentTop(); // draw data int i = 0; while (values.hasNext()) { E value = values.next(); double valY = value.getY() - minY; double ratY = valY / diffY; double y = contentHeight * ratY; double valY0 = 0 - minY; double ratY0 = valY0 / diffY; double y0 = contentHeight * ratY0; double valueX = value.getX(); double valX = valueX - minX; double ratX = valX / diffX; double x = contentWidth * ratX; // hook for value dependent color if (getValueDependentColor() != null) { mPaint.setColor(getValueDependentColor().get(value)); } else { mPaint.setColor(getColor()); } double left = x + contentLeft - offset + spacing / 2 + currentSeriesOrder * barWidth; double top = (contentTop - y) + contentHeight; double right = left + barWidth; double bottom = (contentTop - y0) + contentHeight - (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1); boolean reverse = top > bottom; if (mAnimated) { if ((Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) { long currentTime = System.currentTimeMillis(); if (mAnimationStart == 0) { // start animation mAnimationStart = currentTime; mAnimationStartFrameNo = 0; } else { // anti-lag: wait a few frames if (mAnimationStartFrameNo < 15) { // second time mAnimationStart = currentTime; mAnimationStartFrameNo++; } } float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION; float factor = mAnimationInterpolator.getInterpolation(timeFactor); if (timeFactor <= 1.0) { double barHeight = bottom - top; barHeight = barHeight * factor; top = bottom - barHeight; ViewCompat.postInvalidateOnAnimation(graphView); } else { // animation finished mLastAnimatedValue = valueX; } } } if (reverse) { double tmp = top; top = bottom + (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1); bottom = tmp; } // overdraw left = Math.max(left, contentLeft); right = Math.min(right, contentLeft + contentWidth); bottom = Math.min(bottom, contentTop + contentHeight); top = Math.max(top, contentTop); mDataPoints.put(new RectD(left, top, right, bottom), value); Paint p; if (mCustomPaint != null) { p = mCustomPaint; } else { p = mPaint; } canvas.drawRect((float) left, (float) top, (float) right, (float) bottom, p); // set values on top of graph if (mDrawValuesOnTop) { if (reverse) { top = bottom + mValuesOnTopSize + 4; if (top > contentTop + contentHeight) top = contentTop + contentHeight; } else { top -= 4; if (top <= contentTop) top += contentTop + 4; } mPaint.setColor(mValuesOnTopColor); canvas.drawText( graphView.getGridLabelRenderer().getLabelFormatter().formatLabel(value.getY(), false), (float) (left + right) / 2, (float) top, mPaint); } i++; } }
From source file:com.example.firstocr.ViewfinderView.java
@SuppressWarnings("unused") @Override/*w w w . j ava2 s .c o m*/ public void onDraw(Canvas canvas) { Rect frame = cameraManager.getFramingRect(); if (frame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); // Draw the exterior (i.e. outside the framing rect) darkened paint.setColor(maskColor); canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); canvas.drawRect(0, frame.bottom + 1, width, height, paint); // If we have an OCR result, overlay its information on the viewfinder. if (resultText != null) { // Only draw text/bounding boxes on viewfinder if it hasn't been resized since the OCR was requested. Point bitmapSize = resultText.getBitmapDimensions(); previewFrame = cameraManager.getFramingRectInPreview(); if (bitmapSize.x == previewFrame.width() && bitmapSize.y == previewFrame.height()) { float scaleX = frame.width() / (float) previewFrame.width(); float scaleY = frame.height() / (float) previewFrame.height(); if (DRAW_REGION_BOXES) { regionBoundingBoxes = resultText.getRegionBoundingBoxes(); for (int i = 0; i < regionBoundingBoxes.size(); i++) { paint.setAlpha(0xA0); paint.setColor(Color.MAGENTA); paint.setStyle(Style.STROKE); paint.setStrokeWidth(1); rect = regionBoundingBoxes.get(i); canvas.drawRect(frame.left + rect.left * scaleX, frame.top + rect.top * scaleY, frame.left + rect.right * scaleX, frame.top + rect.bottom * scaleY, paint); } } if (DRAW_TEXTLINE_BOXES) { // Draw each textline textlineBoundingBoxes = resultText.getTextlineBoundingBoxes(); paint.setAlpha(0xA0); paint.setColor(Color.RED); paint.setStyle(Style.STROKE); paint.setStrokeWidth(1); for (int i = 0; i < textlineBoundingBoxes.size(); i++) { rect = textlineBoundingBoxes.get(i); canvas.drawRect(frame.left + rect.left * scaleX, frame.top + rect.top * scaleY, frame.left + rect.right * scaleX, frame.top + rect.bottom * scaleY, paint); } } if (DRAW_STRIP_BOXES) { stripBoundingBoxes = resultText.getStripBoundingBoxes(); paint.setAlpha(0xFF); paint.setColor(Color.YELLOW); paint.setStyle(Style.STROKE); paint.setStrokeWidth(1); for (int i = 0; i < stripBoundingBoxes.size(); i++) { rect = stripBoundingBoxes.get(i); canvas.drawRect(frame.left + rect.left * scaleX, frame.top + rect.top * scaleY, frame.left + rect.right * scaleX, frame.top + rect.bottom * scaleY, paint); } } if (DRAW_WORD_BOXES || DRAW_WORD_TEXT) { // Split the text into words wordBoundingBoxes = resultText.getWordBoundingBoxes(); // for (String w : words) { // Log.e("ViewfinderView", "word: " + w); // } //Log.d("ViewfinderView", "There are " + words.length + " words in the string array."); //Log.d("ViewfinderView", "There are " + wordBoundingBoxes.size() + " words with bounding boxes."); } if (DRAW_WORD_BOXES) { paint.setAlpha(0xFF); paint.setColor(0xFF00CCFF); paint.setStyle(Style.STROKE); paint.setStrokeWidth(1); for (int i = 0; i < wordBoundingBoxes.size(); i++) { // Draw a bounding box around the word rect = wordBoundingBoxes.get(i); canvas.drawRect(frame.left + rect.left * scaleX, frame.top + rect.top * scaleY, frame.left + rect.right * scaleX, frame.top + rect.bottom * scaleY, paint); } } if (DRAW_WORD_TEXT) { words = resultText.getText().replace("\n", " ").split(" "); int[] wordConfidences = resultText.getWordConfidences(); for (int i = 0; i < wordBoundingBoxes.size(); i++) { boolean isWordBlank = true; try { if (!words[i].equals("")) { isWordBlank = false; } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } // Only draw if word has characters if (!isWordBlank) { // Draw a white background around each word rect = wordBoundingBoxes.get(i); paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); if (DRAW_TRANSPARENT_WORD_BACKGROUNDS) { // Higher confidence = more opaque, less transparent background paint.setAlpha(wordConfidences[i] * 255 / 100); } else { paint.setAlpha(255); } canvas.drawRect(frame.left + rect.left * scaleX, frame.top + rect.top * scaleY, frame.left + rect.right * scaleX, frame.top + rect.bottom * scaleY, paint); // Draw the word in black text paint.setColor(Color.BLACK); paint.setAlpha(0xFF); paint.setAntiAlias(true); paint.setTextAlign(Align.LEFT); // Adjust text size to fill rect paint.setTextSize(100); paint.setTextScaleX(1.0f); // ask the paint for the bounding rect if it were to draw this text Rect bounds = new Rect(); paint.getTextBounds(words[i], 0, words[i].length(), bounds); // get the height that would have been produced int h = bounds.bottom - bounds.top; // figure out what textSize setting would create that height of text float size = (((float) (rect.height()) / h) * 100f); // and set it into the paint paint.setTextSize(size); // Now set the scale. // do calculation with scale of 1.0 (no scale) paint.setTextScaleX(1.0f); // ask the paint for the bounding rect if it were to draw this text. paint.getTextBounds(words[i], 0, words[i].length(), bounds); // determine the width int w = bounds.right - bounds.left; // calculate the baseline to use so that the entire text is visible including the descenders int text_h = bounds.bottom - bounds.top; int baseline = bounds.bottom + ((rect.height() - text_h) / 2); // determine how much to scale the width to fit the view float xscale = ((float) (rect.width())) / w; // set the scale for the text paint paint.setTextScaleX(xscale); canvas.drawText(words[i], frame.left + rect.left * scaleX, frame.top + rect.bottom * scaleY - baseline, paint); } } } // if (DRAW_CHARACTER_BOXES || DRAW_CHARACTER_TEXT) { // characterBoundingBoxes = resultText.getCharacterBoundingBoxes(); // } // // if (DRAW_CHARACTER_BOXES) { // // Draw bounding boxes around each character // paint.setAlpha(0xA0); // paint.setColor(0xFF00FF00); // paint.setStyle(Style.STROKE); // paint.setStrokeWidth(1); // for (int c = 0; c < characterBoundingBoxes.size(); c++) { // Rect characterRect = characterBoundingBoxes.get(c); // canvas.drawRect(frame.left + characterRect.left * scaleX, // frame.top + characterRect.top * scaleY, // frame.left + characterRect.right * scaleX, // frame.top + characterRect.bottom * scaleY, paint); // } // } // // if (DRAW_CHARACTER_TEXT) { // // Draw letters individually // for (int i = 0; i < characterBoundingBoxes.size(); i++) { // Rect r = characterBoundingBoxes.get(i); // // // Draw a white background for every letter // int meanConfidence = resultText.getMeanConfidence(); // paint.setColor(Color.WHITE); // paint.setAlpha(meanConfidence * (255 / 100)); // paint.setStyle(Style.FILL); // canvas.drawRect(frame.left + r.left * scaleX, // frame.top + r.top * scaleY, // frame.left + r.right * scaleX, // frame.top + r.bottom * scaleY, paint); // // // Draw each letter, in black // paint.setColor(Color.BLACK); // paint.setAlpha(0xFF); // paint.setAntiAlias(true); // paint.setTextAlign(Align.LEFT); // String letter = ""; // try { // char c = resultText.getText().replace("\n","").replace(" ", "").charAt(i); // letter = Character.toString(c); // // if (!letter.equals("-") && !letter.equals("_")) { // // // Adjust text size to fill rect // paint.setTextSize(100); // paint.setTextScaleX(1.0f); // // // ask the paint for the bounding rect if it were to draw this text // Rect bounds = new Rect(); // paint.getTextBounds(letter, 0, letter.length(), bounds); // // // get the height that would have been produced // int h = bounds.bottom - bounds.top; // // // figure out what textSize setting would create that height of text // float size = (((float)(r.height())/h)*100f); // // // and set it into the paint // paint.setTextSize(size); // // // Draw the text as is. We don't really need to set the text scale, because the dimensions // // of the Rect should already be suited for drawing our letter. // canvas.drawText(letter, frame.left + r.left * scaleX, frame.top + r.bottom * scaleY, paint); // } // } catch (StringIndexOutOfBoundsException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } } } // Draw a two pixel solid border inside the framing rect paint.setAlpha(0); paint.setStyle(Style.FILL); paint.setColor(frameColor); canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint); canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint); canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint); canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint); // Draw the framing rect corner UI elements paint.setColor(cornerColor); canvas.drawRect(frame.left - 15, frame.top - 15, frame.left + 15, frame.top, paint); canvas.drawRect(frame.left - 15, frame.top, frame.left, frame.top + 15, paint); canvas.drawRect(frame.right - 15, frame.top - 15, frame.right + 15, frame.top, paint); canvas.drawRect(frame.right, frame.top - 15, frame.right + 15, frame.top + 15, paint); canvas.drawRect(frame.left - 15, frame.bottom, frame.left + 15, frame.bottom + 15, paint); canvas.drawRect(frame.left - 15, frame.bottom - 15, frame.left, frame.bottom, paint); canvas.drawRect(frame.right - 15, frame.bottom, frame.right + 15, frame.bottom + 15, paint); canvas.drawRect(frame.right, frame.bottom - 15, frame.right + 15, frame.bottom + 15, paint); // Request another update at the animation interval, but don't repaint the entire viewfinder mask. //postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); }