protected void drawLegend(Canvas canvas, float height, float width) { float textSize = paint.getTextSize(); int spacing = getGraphViewStyle().getLegendSpacing(); int border = getGraphViewStyle().getLegendBorder(); int legendWidth = getGraphViewStyle().getLegendWidth(); int shapeSize = (int) (textSize * 0.8d); Log.d("GraphView", "draw legend size: " + paint.getTextSize()); // rect paint.setARGB(180, 100, 100, 100); float legendHeight = (shapeSize + spacing) * graphSeries.size() + 2 * border - spacing; float lLeft = width - legendWidth - border * 2; float lTop; switch (legendAlign) { case TOP: lTop = 0; break; case MIDDLE: lTop = height / 2 - legendHeight / 2; break; default: lTop = height - GraphViewConfig.BORDER - legendHeight - getGraphViewStyle().getLegendMarginBottom(); } float lRight = lLeft + legendWidth; float lBottom = lTop + legendHeight; canvas.drawRoundRect(new RectF(lLeft, lTop, lRight, lBottom), 8, 8, paint); for (int i = 0; i < graphSeries.size(); i++) { paint.setColor(graphSeries.get(i).style.color); canvas.drawRect( new RectF( lLeft + border, lTop + border + (i * (shapeSize + spacing)), lLeft + border + shapeSize, lTop + border + (i * (shapeSize + spacing)) + shapeSize), paint); if (graphSeries.get(i).description != null) { paint.setColor(Color.WHITE); paint.setTextAlign(Align.LEFT); canvas.drawText( graphSeries.get(i).description, lLeft + border + shapeSize + spacing, lTop + border + shapeSize + (i * (shapeSize + spacing)), paint); } } }
private void drawTradeMark(Canvas canvas) { Rect framingRect = getFramingRect(); float tradeMarkTop; float tradeMarkLeft; if (framingRect != null) { tradeMarkTop = framingRect.bottom + PAINT.getTextSize() + 10; tradeMarkLeft = framingRect.left; } else { tradeMarkTop = 10; tradeMarkLeft = canvas.getHeight() - PAINT.getTextSize() - 10; } canvas.drawText(TRADE_MARK_TEXT, tradeMarkLeft, tradeMarkTop, PAINT); }
void drawTestBox(Canvas cv, RectF r, float rot, String text) { cv.save(); cv.translate(r.centerX(), r.centerY()); cv.rotate((float) (rot * 180 / Math.PI)); RectF rs = new RectF(-r.width() / 2, -r.height() / 2, r.width() / 2, r.height() / 2); cv.drawRect(rs, paintIcon); if (text != null) { paintText.setTextSize(paintText.getTextSize() - 4); cv.drawText(text, rs.centerX(), rs.centerY(), paintText); paintText.setTextSize(paintText.getTextSize() + 4); } cv.restore(); }
@Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { // Get the map projection to convert lat/long to screen coordinates Projection projection = mapView.getProjection(); Point lPoint = new Point(); projection.toPixels(locationPoint, lPoint); // Draw the overlay if (shadow == false) { if (friendLocations.size() > 0) { Iterator<String> e = friendLocations.keySet().iterator(); do { // Get the name and location of each contact String name = e.next(); Location location = friendLocations.get(name); // Convert the lat / long to a Geopoint Double latitude = location.getLatitude() * 1E6; Double longitude = location.getLongitude() * 1E6; GeoPoint geopoint = new GeoPoint(latitude.intValue(), longitude.intValue()); // Ensure each contact is within 10km float dist = location.distanceTo(getLocation()); if (dist < 10000) { Point point = new Point(); projection.toPixels(geopoint, point); // Draw a line connecting the contact to your current location. canvas.drawLine(lPoint.x, lPoint.y, point.x, point.y, paint); // Draw a marker at the contact's location. RectF oval = new RectF( point.x - markerRadius, point.y - markerRadius, point.x + markerRadius, point.y + markerRadius); canvas.drawOval(oval, backPaint); oval.inset(2, 2); canvas.drawOval(oval, paint); // Draw the contact's name next to their position. float textWidth = paint.measureText(name); float textHeight = paint.getTextSize(); RectF textRect = new RectF( point.x + markerRadius, point.y - textHeight, point.x + markerRadius + 8 + textWidth, point.y + 4); canvas.drawRoundRect(textRect, 3, 3, backPaint); canvas.drawText(name, point.x + markerRadius + 4, point.y, paint); } } while (e.hasNext()); } } super.draw(canvas, mapView, shadow); }
/** * Generates bitmap used for drawing button. * * @param radius Radius of button in pixels. */ @Override void generateBitmap() { super.generateBitmap(); // Size and shape buttonShape.setShape(new OvalShape()); buttonShape.setBounds( new Rect(PADDING, PADDING, (int) radius * 2 - PADDING, (int) radius * 2 - PADDING)); // Create button bitmap and render shape buttonBitmap = Bitmap.createBitmap((int) radius * 2, (int) radius * 2, Bitmap.Config.ARGB_4444); Canvas handleCanvas = new Canvas(buttonBitmap); buttonShape.getPaint().set(parent.fillPaint); buttonShape.draw(handleCanvas); // Set text style textPaint.setStyle(Paint.Style.FILL); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setColor(Color.BLACK); // Set size (one character has a standard design, more has dynamic size) if (label.length() == 1) textPaint.setTextSize(radius); else textPaint.setTextSize(radius / label.length() * 2.5f); // Set paint to clear text from button textPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); // Render the button handleCanvas.drawText(label, radius, radius + (textPaint.getTextSize() * .33333f), textPaint); }
@Override protected void onDraw(Canvas canvas) { int width = getWidth() - getPaddingLeft() - getPaddingRight(); int height = getHeight() - getPaddingTop() - getPaddingBottom(); if (backgroundDrawable != null) { int dw = backgroundDrawable.getIntrinsicWidth(); int left = getPaddingLeft() + (width - dw) / 2; int top = getPaddingTop(); int right = left + dw; int bottom = height + getPaddingTop(); backgroundDrawable.setBounds(left, top, right, bottom); backgroundDrawable.draw(canvas); } if (progressDrawable != null) { int dw = progressDrawable.getIntrinsicWidth(); int left = getPaddingLeft() + (width - dw) / 2; int top = getPaddingTop(); int right = left + dw; int bottom = height + getPaddingTop(); progressDrawable.setBounds(left, top, right, bottom); progressDrawable.setLevel((int) (10000 * progress.percentage())); progressDrawable.draw(canvas); } int textWidth = (int) paint.measureText(progress.toString()); int x = (width - textWidth) / 2 + getPaddingLeft(); int y = height / 2 + getPaddingTop() - (int) (paint.getTextSize() / 2); canvas.drawText(progress.toString(), x, y, paint); }
/** * @param textview * @return */ private String adjustTextLength(TextView tv) { if (tv == null) { return ""; } String input = tv.getText().toString(); String result = input; String newtext = input; int lastSpaceIndex = 0; ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) tv.getLayoutParams(); Paint p = tv.getPaint(); Rect bound = new Rect(); p.getTextBounds(input, 0, input.length() - 1, bound); float textHeight = p.getTextSize(); float multiLine = (((lp.height - tv.getPaddingTop() - tv.getPaddingBottom()) / textHeight)); float availableW = (lp.width - tv.getPaddingLeft() - tv.getPaddingRight()) * (multiLine + 0.2f); do { newtext = (String) TextUtils.ellipsize(result, tv.getPaint(), availableW, TruncateAt.END); if (!newtext.equals(result)) { lastSpaceIndex = newtext.lastIndexOf(" "); if (lastSpaceIndex > 0) { result = newtext.substring(0, lastSpaceIndex) + "..."; } else { break; } } else { break; } } while (false); GKIMLog.lf(null, 0, TAG + "=>adjust title from: " + input + " to: " + result); tv.setText(result); return result; }
/** * * Allocate the paint object and figuring out how large the instrument is on the display based * upon the text size in the source paint object * * @param textPaint Used to figure out our overall size */ public void setSize(Paint textPaint) { // A total of 11 bars mBarCount = 11; // The width of each bar is the basis for the entire instrument size mBarWidth = textPaint.getTextSize() * (float) 0.5; // Height is 1/4 of the width mBarHeight = mBarWidth / 4; // Space between bars is 3x the height of the bar mBarSpace = 3 * mBarHeight; // Height of the entire instrument mInstHeight = mBarCount * mBarHeight + // The bars themselves (mBarCount - 1) * mBarSpace + // Space between the bars 2 * mBarHeight; // Space to the top and bottom of the end bars // Width of the entire instrument mInstWidth = mBarWidth + // The main bar itself mBarWidth / 2 + // The triangle indicator height mBarHeight * 3; // Border padding at left/right/middle // Allocate the paint object to save time during draw cycle mVNAVPaint = new Paint(textPaint); }
@Override public void onDraw(final Canvas c) { // Draw the alpha pattern mAlphaPattern.draw(c); // Draw the shader that shows how transparent a colors looks at a given alpha on top of the // alpha pattern shaderPaint.setShader( new LinearGradient( borderSize, 0, this.getWidth() - borderSize, 0, 0, color, TileMode.CLAMP)); c.drawRect( borderSize, borderSize, this.getWidth() - borderSize, this.getHeight() - borderSize, shaderPaint); // Draw the transparency label on top of that stuff c.drawText( "Transparency", this.getWidth() / 2, this.getHeight() / 2 + labelPaint.getTextSize() / 2.0f, labelPaint); // Draw the alpha tracker on top of everything else final float xPos = alphaToXPos(alpha); final float rectWidth = 2 * mDensity; final RectF r = new RectF(); r.left = xPos - rectWidth; r.right = xPos + rectWidth; r.top = 0; r.bottom = this.getHeight(); c.drawRoundRect(r, rectWidth, rectWidth, trackerPaint); }
protected void onDrawCell(Canvas canvas, Cell cell) { if (cell.text == null && cell.bgColor == null && cell.rtDrawable == null) return; // 如果无内容,且无背景色不进行绘制 Rect rect = this.getCellRectInView(cell); if (cell.bgColor != null) { canvas.drawColor(cell.bgColor); } if (cell.ballColor != null) { painter.setColor(cell.ballColor); canvas.drawCircle(rect.centerX(), rect.centerY(), rect.height() / 2 - 1 * dp, painter); } if (cell.textColor != null) painter.setColor(cell.textColor); if (cell.text != null) { if (cell.textSize > 0) painter.setTextSize(cell.textSize); else painter.setTextSize(this.textSize); painter.setTextAlign(cell.aligin); int cx = rect.centerX(); if (cell.aligin == Align.LEFT) cx = rect.left; else if (cell.aligin == Align.RIGHT) cx = rect.right; int cy = rect.centerY() + (int) (painter.getTextSize() * 2 / 5 + 0.5f); if (cell.fixedTextX) cx -= offX; if (cell.fixedTextY) cy -= offY; canvas.drawText(cell.text, cx, cy, painter); } if (cell.rtDrawable != null) { int minWidth = cell.rtDrawable.getMinimumWidth(); if (minWidth > rect.width() / 2) minWidth = rect.width() / 2; cell.rtDrawable.setBounds( new Rect(rect.right - minWidth, rect.top, rect.right, rect.top + minWidth)); cell.rtDrawable.draw(canvas); } }
// 设置字体大小 public final void setTextSize(float size) { if (size != paint.getTextSize()) { mFontSize = size; if (mTextHeight > 0) { GetTextInfo(); } } }
@Override public void onDraw(Canvas canvas) { super.onDraw(canvas); // Translate the canvas to account for the view padding canvas.translate(mCanvasXPadding, mCanvasYPadding); // Outside box mCacheRectF.set(0, 0, mWidth, mHeight); canvas.drawRect(mCacheRectF, mStrokeColor); final float centerY = mHeight / 2; final float ticMargin = mHeight / mScrollToRange; final int start = (int) (mScrollTo - mScrollToRange / 2); final int end = (int) (mScrollTo + mScrollToRange / 2); final float ticStart = mHandedness == Handedness.LEFT ? mWidth : 0; final float ticEnd = mHandedness == Handedness.LEFT ? ticStart - mTicWidth : ticStart + mTicWidth; final float textStart = mHandedness == Handedness.LEFT ? mWidth - mTextHorizontalMargin : mTextHorizontalMargin; final float textOffset = mStrokeColor.getTextSize() / 2 + mTextVerticalMargin; for (int a = start; a <= end; a++) { if (a % 5 == 0) { float lineHeight = centerY - ticMargin * (a - mScrollTo); canvas.drawLine(ticStart, lineHeight, ticEnd, lineHeight, mStrokeColor); canvas.drawText(String.valueOf(a), textStart, lineHeight + textOffset, mStrokeColor); } } // Arrow with current speed final int borderWidth = Math.round(mArrowStrokeColor.getStrokeWidth()); final float arrowStickX, arrowBaseX, arrowPointX; if (mHandedness == Handedness.LEFT) { arrowStickX = -borderWidth; arrowBaseX = mWidth - mArrowHeight / 4 - borderWidth; arrowPointX = mWidth - borderWidth; } else { arrowStickX = mWidth + borderWidth; arrowBaseX = mArrowHeight / 4 + borderWidth; arrowPointX = borderWidth; } final float arrowStartY = centerY - mArrowHeight / 2; final float arrowEndY = centerY + mArrowHeight / 2; mCachePath.reset(); Path arrow = mCachePath; arrow.moveTo(arrowStickX, arrowStartY); arrow.lineTo(arrowBaseX, arrowStartY); arrow.lineTo(arrowPointX, centerY); arrow.lineTo(arrowBaseX, arrowEndY); arrow.lineTo(arrowStickX, arrowEndY); canvas.drawPath(arrow, mArrowBgColor); canvas.drawPath(arrow, mArrowStrokeColor); canvas.drawText(String.valueOf((int) mScrollTo), textStart, centerY + textOffset, mStrokeColor); }
private void adjustSayingText(Paint mSayingPaint, String textToMeasure) { if (mSayingPaint.measureText(textToMeasure, 0, textToMeasure.length()) <= getDisplayMetrics().widthPixels) { return; } else { mSayingPaint.setTextSize(mSayingPaint.getTextSize() - 0.1f); adjustSayingText(mSayingPaint, textToMeasure); } }
private void adjustSayingTextRound(Paint mSayingPaint, String textToMeasure) { if (mSayingPaint.measureText(textToMeasure, 0, textToMeasure.length()) <= boundary.getRectWidth()) { return; } else { mSayingPaint.setTextSize(mSayingPaint.getTextSize() - 0.1f); adjustSayingTextRound(mSayingPaint, textToMeasure); } }
private void drawFocusRect(RectF rect, int color) { canvas = holderTransparent.lockCanvas(); canvas.drawColor(0, PorterDuff.Mode.CLEAR); // border's properties Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setColor(color); paint.setStrokeWidth(3); paint.setTextSize(paint.getTextSize() * 7); canvas.drawRect(rect, paint); holderTransparent.unlockCanvasAndPost(canvas); }
@Override public void handleTile( final Canvas pCanvas, final int pTileSizePx, final MapTile pTile, final int pX, final int pY) { // no overflow detected here Log.d(IMapView.LOGTAG, "handleTile " + pTile.toString() + // ","+pX + "," + pY); Drawable currentMapTile = mTileProvider.getMapTile(pTile); boolean isReusable = currentMapTile instanceof ReusableBitmapDrawable; final ReusableBitmapDrawable reusableBitmapDrawable = isReusable ? (ReusableBitmapDrawable) currentMapTile : null; if (currentMapTile == null) { currentMapTile = getLoadingTile(); } if (currentMapTile != null) { mTilePoint.set(pX * pTileSizePx, pY * pTileSizePx); mTileRect.set( mTilePoint.x, mTilePoint.y, mTilePoint.x + pTileSizePx, mTilePoint.y + pTileSizePx); if (isReusable) { reusableBitmapDrawable.beginUsingDrawable(); } try { if (isReusable && !((ReusableBitmapDrawable) currentMapTile).isBitmapValid()) { currentMapTile = getLoadingTile(); isReusable = false; } onTileReadyToDraw(pCanvas, currentMapTile, mTileRect); } finally { if (isReusable) reusableBitmapDrawable.finishUsingDrawable(); } } if (DEBUGMODE) { mTileRect.set( pX * pTileSizePx, pY * pTileSizePx, pX * pTileSizePx + pTileSizePx, pY * pTileSizePx + pTileSizePx); pCanvas.drawText( pTile.toString(), mTileRect.left + 1, mTileRect.top + mDebugPaint.getTextSize(), mDebugPaint); pCanvas.drawLine( mTileRect.left, mTileRect.top, mTileRect.right, mTileRect.top, mDebugPaint); pCanvas.drawLine( mTileRect.left, mTileRect.top, mTileRect.left, mTileRect.bottom, mDebugPaint); } }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = resolveSize(50, widthMeasureSpec); // Get the desired height of the icon menu view (last row of items does // not have a divider below) Rect padding = new Rect(); mSelectionHighlight.getPadding(padding); final int desiredHeight = ((int) mPaint.getTextSize()) + mVerticalPadding + padding.top + padding.bottom; // Maximum possible width and desired height setMeasuredDimension(measuredWidth, resolveSize(desiredHeight, heightMeasureSpec)); }
protected void drawAxesLabels(Canvas canvas) { canvas.drawText( mXAxisLabel, mLeftPadding + graphWidth / 2 - mAxisLabelPaint.measureText(mXAxisLabel) / 2, mTopPadding + graphHeight + mBottomPadding - mXAxisLabelOffset, mAxisLabelPaint); canvas.rotate(-90, 0, 0); canvas.drawText( mYAxisLabel, -(mTopPadding + graphHeight / 2 + mAxisLabelPaint.measureText(mYAxisLabel) / 2), mAxisLabelPaint.getTextSize() + mYAxisLabelOffset, mAxisLabelPaint); canvas.rotate(90, 0, 0); }
@Override protected void onDraw(Canvas canvas) { float textShowWidth = getWidth(); Paint textPaint = getPaint(); float textSize = textPaint.getTextSize(); int lineCount; // 当前行数 float oneX; // 当前一个汉字绘制的x坐标 float oneY = 0; // 当前一个汉字绘制的y坐标 String text = this.getText().toString(); if (TextUtils.isEmpty(text)) { return; } char[] textCharArray = text.toCharArray(); if (logCount == 1) { Log.i("TAG", "textShowWidth---" + textShowWidth); Log.i("TAG", "textCharArray---" + textCharArray.length); logCount = 2; } ArrayList<LineModel> lineList = getCalculateLineList( textPaint, textCharArray, textShowWidth, isGravityCenter, oneMarginLeft); if (logCount == 2) { Log.i("TAG", "lineList---" + lineList.toString()); logCount = 3; } float charWidth; for (int j = 0; j < lineList.size(); j++) { LineModel model = lineList.get(j); lineCount = model.getLineCount(); oneX = model.getStartX(); if (model.getLineCount() == 1) { oneY = textSize; } if (model.getLineCount() >= 2) { oneY = (lineCount * textSize + (lineCount - 1) * lineSpace); } for (int k = model.getStartIndex(); k < model.getEndIndex() + 1; k++) { charWidth = textPaint.measureText(textCharArray, k, 1); canvas.drawText(textCharArray, k, 1, oneX, oneY, textPaint); oneX = charWidth + oneMarginLeft + oneX; } } setHeight((int) (oneY + bottomSpace)); }
protected void drawAxes(Canvas canvas) { float textHoriOffset; float textVertOffset = -(2 * mAxesPaint.getTextSize() - mAxesPaint.getFontSpacing()) / 2; Path axesPath = new Path(); axesPath.moveTo(mLeftPadding, mTopPadding - mGridlinesPaint.getStrokeWidth() / 2); axesPath.lineTo(mLeftPadding, mTopPadding + graphHeight); axesPath.lineTo( mLeftPadding + graphWidth + mGridlinesPaint.getStrokeWidth() / 2, mTopPadding + graphHeight); mAxesPaint.setStyle(Paint.Style.STROKE); mAxesPaint.setAntiAlias(false); canvas.drawPath(axesPath, mAxesPaint); mAxesPaint.setAntiAlias(mAxesPaintAntiAlias); mAxesPaint.setStyle(Paint.Style.FILL); for (int i = 0; i < mYAxisLabels.length; i++) { textHoriOffset = mAxesPaint.measureText(mYAxisLabels[i]) + mGridlineLabelHoriSpacing; canvas.drawText( mYAxisLabels[i], mLeftPadding - textHoriOffset, mTopPadding - textVertOffset + (1.00f - mYAxisLabelPositions[i]) * graphHeight, mAxesPaint); } textVertOffset = (2 * mAxesPaint.getTextSize() - mAxesPaint.getFontSpacing()) + mGridlineLabelVertSpacing; for (int i = 0; i < mXAxisLabels.length; i++) { textHoriOffset = mAxesPaint.measureText(mXAxisLabels[i]) / 2; canvas.drawText( mXAxisLabels[i], mLeftPadding - textHoriOffset + mXAxisLabelPositions[i] * graphWidth, mTopPadding + graphHeight + textVertOffset, mAxesPaint); } }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setTypeface(Typeface.create("", Typeface.BOLD)); paint.setTextSize((int) (textSize * BaseActivity.screen_width)); paint.setAntiAlias(true); paint.setColor(Color.rgb(100, 100, 100)); float x = Utils.measureX(paint, AVAILABLE_BALANCE_TITLE, maxwidth); canvas.drawText(AVAILABLE_BALANCE_TITLE, x, (float) (availableY * maxHeight), paint); x = Utils.measureX(paint, ACCOUNT_BALANCE_TITLE, maxwidth); canvas.drawText(ACCOUNT_BALANCE_TITLE, x, (float) ((accountY) * maxHeight), paint); x = Utils.measureX(paint, ACCOUNT_BALANCE_TITLE, maxwidth); canvas.drawText(ACCOUNT_BALANCE_TITLE, x, (float) ((accountY) * maxHeight), paint); paint.setColor(Color.BLACK); x = Utils.measureX(paint, getAvailableBalanceValue(), maxwidth); canvas.drawText( getAvailableBalanceValue(), x, (float) ((availableY + line) * maxHeight), paint); x = Utils.measureX(paint, getAccountBalanceValue(), maxwidth); canvas.drawText(getAccountBalanceValue(), x, (float) ((accountY + line) * maxHeight), paint); x = (float) (maxwidth / 2 - paint.measureText(DEPOSIT_TITLE) - placeholderLineDrawableWidth); canvas.drawText(DEPOSIT_TITLE, x, (float) ((depositY) * maxHeight), paint); x = (float) (maxwidth / 2 + placeholderLineDrawableWidth); canvas.drawText(WITHDRAWALS_TITLE, x, (float) ((depositY) * maxHeight), paint); x = (float) (maxwidth / 2 - paint.measureText(getDepositValue()) - placeholderLineDrawableWidth); canvas.drawText(getDepositValue(), x, (float) ((depositY + line) * maxHeight), paint); x = (float) (maxwidth / 2 + placeholderLineDrawableWidth); canvas.drawText(getWidthdrawalsValue(), x, (float) ((depositY + line) * maxHeight), paint); if (placeholderLineDrawable != null) { canvas.save(); // canvas.scale((float)xx, (float)xx); canvas.translate((float) (o_x), (float) ((depositY) * maxHeight) - paint.getTextSize()); placeholderLineDrawable.draw(canvas); canvas.restore(); } }
/** * 绘制文字 * * @param canvas * @param text * @param x * @param y * @param paint * @param angle * @param zoom */ protected void drawText( Canvas canvas, String text, float x, float y, Paint paint, float angle, float zoom) { // 缩放 Paint textPaint = new Paint(paint); textPaint.setTextSize(paint.getTextSize() * zoom); // 旋转 canvas.save(); canvas.rotate(angle, x, y); x -= (getFontWidth(textPaint, text) - getFontWidth(paint, text)) / 2; y += (getFontHeight(textPaint) - getFontHeight(paint)) / 2; canvas.drawText(text, x, y, textPaint); canvas.restore(); }
/** * * The main display is telling us what paint it is using. Make a copy of it and adjust it for * what we need it to do. Perform some size calculations here instead of at draw time * * @param paint */ public void setPaint(Paint paint) { // Allocate our own paint based upon what is in use mPaint = new Paint(paint); // Set our desired attributes mPaint.setTextSize(mPaint.getTextSize() / (float) 2.5); mPaint.setTextAlign(Align.LEFT); // Find out how big our shadow needs to be mPaint.getTextBounds("000", 0, 3, mTextBounds); // Determine the margin pixel values mTextWidth = mTextBounds.width(); mTextHeight = mTextBounds.height(); mBgndWidth = (int) (mTextWidth * 1.4); mLeftMargin = (int) (mTextWidth * 0.2); mBgndHeight = (int) (mTextHeight * 1.4); mBotmMargin = (int) (mTextHeight * 1.2); }
/** * Helper to draw this square in its current color (whichever that is). * * <p>This method does not modify any settings of the Paint object passed to it. * * @param canvas Canvas object to draw to * @param paint Paint object to use for the drawing */ public void draw(Canvas canvas, Paint paint) { int oldColor = paint.getColor(); paint.setColor(this.color); canvas.drawRect(this.xpos, this.ypos, this.xpos + this.width, this.ypos + this.height, paint); if (text != null) { Paint.Align oldAlign = paint.getTextAlign(); float oldSize = paint.getTextSize(); paint.setTextAlign(Paint.Align.CENTER); paint.setColor(textColor); paint.setTextSize(0.8f * this.height); canvas.drawText( this.text, this.xpos + this.width / 2, this.ypos + 4 * this.height / 5, paint); paint.setTextAlign(oldAlign); paint.setTextSize(oldSize); } paint.setColor(oldColor); }
/** * Applies the specified text appearance resource to a paint, returning the text color if one is * set in the text appearance. * * @param p the paint to modify * @param resId the resource ID of the text appearance * @return the text color, if available */ private ColorStateList applyTextAppearance(Paint p, int resId) { final TypedArray ta = mContext.obtainStyledAttributes(null, R.styleable.TextAppearance, 0, resId); final String fontFamily = ta.getString(R.styleable.TextAppearance_fontFamily); if (fontFamily != null) { p.setTypeface(Typeface.create(fontFamily, 0)); } p.setTextSize( ta.getDimensionPixelSize(R.styleable.TextAppearance_textSize, (int) p.getTextSize())); final ColorStateList textColor = ta.getColorStateList(R.styleable.TextAppearance_textColor); if (textColor != null) { final int enabledColor = textColor.getColorForState(ENABLED_STATE_SET, 0); p.setColor(enabledColor); } ta.recycle(); return textColor; }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.i( "tonghu", "Xfermoders.SampleView-onDraw :" + canvas.getWidth() + ", " + canvas.getHeight()); canvas.drawColor(Color.WHITE); canvas.translate(15, 35); int x = 0; int y = 0; for (int i = 0; i < sModes.length; i++) { paint.setShader(null); paint.setColor(Color.BLACK); paint.setStyle(Style.STROKE); canvas.drawRect(x - 0.5f, y - 0.5f, x + W + 0.5f, y + H + 0.5f, paint); paint.setShader(bg); paint.setStyle(Style.FILL); canvas.drawRect(x, y, x + W, y + H, paint); paint.setShader(null); int saveLayer = canvas.saveLayer(x, y, x + W, y + H, paint, Canvas.ALL_SAVE_FLAG); canvas.drawBitmap(dstB, x, y, paint); paint.setXfermode(sModes[i]); canvas.drawBitmap(srcB, x, y, paint); canvas.drawText(labels[i], x + W / 2, y - labelP.getTextSize() / 2, labelP); paint.setXfermode(null); canvas.restoreToCount(saveLayer); x += W + 10; if ((i % ROW_MAX) == ROW_MAX - 1) { x = 0; y += H + 30; } } }
// Workaround to fix missing text on Lollipop and above, // and probably some rendering issues with Jelly Bean and above // Modified from http://stackoverflow.com/a/14989037/746068 public static void drawTextOnCanvasWithMagnifier( Canvas canvas, String text, float x, float y, Paint paint) { if (android.os.Build.VERSION.SDK_INT <= 15) { // draw normally canvas.drawText(text, x, y, paint); } else { // workaround float originalStrokeWidth = paint.getStrokeWidth(); float originalTextSize = paint.getTextSize(); final float magnifier = 1000f; canvas.save(); canvas.scale(1f / magnifier, 1f / magnifier); paint.setTextSize(originalTextSize * magnifier); paint.setStrokeWidth(originalStrokeWidth * magnifier); canvas.drawText(text, x * magnifier, y * magnifier, paint); canvas.restore(); paint.setTextSize(originalTextSize); paint.setStrokeWidth(originalStrokeWidth); } }
@Override protected void dispatchDraw(Canvas canvas) { if (showcaseX < 0 || showcaseY < 0 || isRedundant) { super.dispatchDraw(canvas); return; } Bitmap b = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); // Draw the semi-transparent background c.drawColor(backColor); // Draw to the scale specified Matrix mm = new Matrix(); mm.postScale(scaleMultiplier, scaleMultiplier, showcaseX, showcaseY); c.setMatrix(mm); // Erase the area for the ring c.drawCircle(showcaseX, showcaseY, showcaseRadius, mEraser); boolean recalculateText = makeVoidedRect() || mAlteredText; mAlteredText = false; showcase.setBounds(voidedArea); showcase.draw(c); canvas.drawBitmap(b, 0, 0, null); // Clean up, as we no longer require these items. try { c.setBitmap(null); } catch (NullPointerException npe) { // TODO why does this NPE happen? npe.printStackTrace(); } b.recycle(); b = null; if (!TextUtils.isEmpty(mTitleText) || !TextUtils.isEmpty(mSubText)) { if (recalculateText) { mBestTextPosition = getBestTextPosition(canvas.getWidth(), canvas.getHeight()); } if (!TextUtils.isEmpty(mTitleText)) { // TODO: use a dynamic detail layout canvas.save(); float width = mPaintTitle.measureText(mTitleText); canvas.rotate( mOrientation, mBestTextPosition[0] + width / 2.0f, mBestTextPosition[1] + mPaintTitle.getTextSize() / 2.0f); canvas.drawText(mTitleText, mBestTextPosition[0], mBestTextPosition[1], mPaintTitle); canvas.restore(); } if (!TextUtils.isEmpty(mSubText)) { canvas.save(); if (recalculateText) mDynamicDetailLayout = new DynamicLayout( mSubText, mPaintDetail, ((Number) mBestTextPosition[2]).intValue(), Layout.Alignment.ALIGN_NORMAL, 1.2f, 1.0f, true); if (mOrientation % 180 == 0) { canvas.translate(mBestTextPosition[0], mBestTextPosition[1]); } else { canvas.rotate( mOrientation, mDynamicDetailLayout.getWidth() / 2, mDynamicDetailLayout.getHeight() / 2); } mDynamicDetailLayout.draw(canvas); canvas.restore(); } } super.dispatchDraw(canvas); }
/** * If the canvas is null, then only touch calculations are performed to pick the target candidate. */ @Override protected void onDraw(Canvas canvas) { // public void draw(Canvas canvas) { if (canvas != null) { super.onDraw(canvas); // super.draw(canvas); } mTotalWidth = 0; if (mSuggestions == null) return; if (mBgPadding == null) { mBgPadding = new Rect(0, 0, 0, 0); if (getBackground() != null) { getBackground().getPadding(mBgPadding); } } int x = 0; final int count = mSuggestions.size(); final int height = getHeight(); final Rect bgPadding = mBgPadding; final Paint paint = mPaint; final int touchX = mTouchX; final int scrollX = getScrollX(); final boolean scrolled = mScrolled; final boolean typedWordValid = mTypedWordValid; final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent()); for (int i = 0; i < count; i++) { String suggestion = mSuggestions.get(i); float textWidth = paint.measureText(suggestion); final int wordWidth = (int) textWidth + X_GAP * 2; mWordX[i] = x; mWordWidth[i] = wordWidth; paint.setColor(mColorNormal); if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) { if (canvas != null) { canvas.translate(x, 0); mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); mSelectionHighlight.draw(canvas); canvas.translate(-x, 0); } mSelectedIndex = i; } if (canvas != null) { if ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid)) { paint.setFakeBoldText(true); paint.setColor(mColorRecommended); } else if (i != 0) { paint.setColor(mColorOther); } canvas.drawText(suggestion, x + X_GAP, y, paint); paint.setColor(mColorOther); canvas.drawLine( x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1, paint); paint.setFakeBoldText(false); } x += wordWidth; } mTotalWidth = x; if (mTargetScrollX != getScrollX()) { scrollToTarget(); } }
public float getTextSize() { return mPaintText.getTextSize(); }