private void calc() { textSize = mHTextView.getTextSize(); paint.setTextSize(textSize); for (int i = 0; i < mText.length(); i++) { gaps[i] = paint.measureText(mText.charAt(i) + ""); } oldPaint.setTextSize(textSize); for (int i = 0; i < mOldText.length(); i++) { oldGaps[i] = oldPaint.measureText(mOldText.charAt(i) + ""); } oldStartX = (mHTextView.getWidth() - oldPaint.measureText(mOldText.toString())) / 2f; startX = (mHTextView.getWidth() - paint.measureText(mText.toString())) / 2f; startY = (int) ((mHTextView.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)); differentList.clear(); differentList.addAll(CharacterUtils.diff(mOldText, mText)); Rect bounds = new Rect(); paint.getTextBounds(mText.toString(), 0, mText.length(), bounds); upDistance = bounds.height(); }
private void prepareAnimate() { mTextSize = mHTextView.getTextSize(); mPaint.setTextSize(mTextSize); for (int i = 0; i < mText.length(); i++) { gaps[i] = mPaint.measureText(mText.charAt(i) + ""); } mOldPaint.setTextSize(mTextSize); for (int i = 0; i < mOldText.length(); i++) { oldGaps[i] = mOldPaint.measureText(mOldText.charAt(i) + ""); } oldStartX = (mHTextView.getMeasuredWidth() - mHTextView.getCompoundPaddingLeft() - mHTextView.getPaddingLeft() - mOldPaint.measureText(mOldText.toString())) / 2f; startX = (mHTextView.getMeasuredWidth() - mHTextView.getCompoundPaddingLeft() - mHTextView.getPaddingLeft() - mPaint.measureText(mText.toString())) / 2f; startY = mHTextView.getBaseline(); differentList.clear(); differentList.addAll(CharacterUtils.diff(mOldText, mText)); }
/* Re size the font so the specified text fits in the text box * assuming the text box is the specified width. */ private void refitText(String text, int textWidth) { if (textWidth <= 0 || text.length() == 0) return; int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight(); // this is most likely a non-relevant call if (targetWidth <= 2) return; // text already fits with the xml-defined font size? mTestPaint.set(this.getPaint()); mTestPaint.setTextSize(defaultTextSize); if (mTestPaint.measureText(text) <= targetWidth) { this.setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize); return; } // adjust text size using binary search for efficiency float hi = defaultTextSize; float lo = 2; final float threshold = 0.5f; // How close we have to be while (hi - lo > threshold) { float size = (hi + lo) / 2; mTestPaint.setTextSize(size); if (mTestPaint.measureText(text) >= targetWidth) hi = size; // too big else lo = size; // too small } // Use lo so that we undershoot rather than overshoot this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo); }
private String[] adjustLineText(String[] text, int adjustLineCount) { if (text.length <= adjustLineCount) return text; float minLength = 0.0f; int minIndex = 0; // check shortest width which lines when combined any two lines. for (int i = 0; i < text.length - 1; ++i) { float length = paint.measureText(text[i]) + paint.measureText(" ") + paint.measureText(text[i + 1]); if (0.0f == minLength || length < minLength) { minLength = length; minIndex = i; } } ArrayList<String> combinedText = new ArrayList<String>(); for (int i = 0; i < text.length; ++i) { if (i == minIndex) { // shortest width, combine next line. combinedText.add(text[i] + " " + text[i + 1]); } else if (i == minIndex + 1) { // combined line, do nothing. continue; } else { // ordinary combinedText.add(text[i]); } } return adjustLineText(combinedText.toArray(new String[0]), adjustLineCount); }
@Override protected synchronized void onDraw(Canvas canvas) { canvas.drawArc(mCircleBounds, 0, 360, false, mBackgroundColorPaint); int prog = getProgress(); float scale = getMax() > 0 ? (float) prog / getMax() * 360 : 0; if (mHasShadow) mProgressColorPaint.setShadowLayer(3, 0, 1, mShadowColor); canvas.drawArc(mCircleBounds, 270, scale, false, mProgressColorPaint); if (!TextUtils.isEmpty(mTitle)) { int xPos = (int) (getMeasuredWidth() / 2 - mTitlePaint.measureText(mTitle) / 2); int yPos = (int) (getMeasuredHeight() / 2); float titleHeight = Math.abs(mTitlePaint.descent() + mTitlePaint.ascent()); if (TextUtils.isEmpty(mSubTitle)) { yPos += titleHeight / 2; } canvas.drawText(mTitle, xPos, yPos, mTitlePaint); yPos += titleHeight; xPos = (int) (getMeasuredWidth() / 2 - mSubtitlePaint.measureText(mSubTitle) / 2); canvas.drawText(mSubTitle, xPos, yPos, mSubtitlePaint); } super.onDraw(canvas); }
protected static Object[] createWrappedLine( String block, Paint paint, float spaceOffset, float maxWidth) { float cacheWidth = maxWidth; float origMaxWidth = maxWidth; String line = ""; for (String word : block.split("\\s")) { cacheWidth = paint.measureText(word); maxWidth -= cacheWidth; if (maxWidth <= 0) { return new Object[] {line, maxWidth + cacheWidth + spaceOffset}; } line += word + " "; maxWidth -= spaceOffset; } if (paint.measureText(block) <= origMaxWidth) { return new Object[] {block, Float.MIN_VALUE}; } return new Object[] {line, maxWidth}; }
/** * Draw the old and new swatches. * * @param canvas */ private void drawSwatches(Canvas canvas) { float[] hsv = new float[3]; mText.setTextSize(16); // Draw the original swatch canvas.drawRect(mOldSwatchRect, mSwatchOld); Color.colorToHSV(mOriginalColor, hsv); // if (UberColorPickerDialog.isGray(mColor)) //Don't need this right here, but imp't to note // hsv[1] = 0; if (hsv[2] > .5) mText.setColor(Color.BLACK); canvas.drawText( "Revert", mOldSwatchRect.left + SWATCH_WIDTH / 2 - mText.measureText("Revert") / 2, mOldSwatchRect.top + 16, mText); mText.setColor(Color.WHITE); // Draw the new swatch canvas.drawRect(mNewSwatchRect, mSwatchNew); if (mHSV[2] > .5) mText.setColor(Color.BLACK); canvas.drawText( "Accept", mNewSwatchRect.left + SWATCH_WIDTH / 2 - mText.measureText("Accept") / 2, mNewSwatchRect.top + 16, mText); mText.setColor(Color.WHITE); mText.setTextSize(TEXT_SIZE); }
public void drawTexts(Canvas canvas) { // level title paint.setTextSize(screenWidth / 15); paint.setColor(Color.YELLOW); canvas.drawText( view.context.getResources().getString(R.string.Level) + " " + view.currentLevel, screenWidth / 10 + screenWidth / 20, (screenHeight - screenWidth) / 2 - screenWidth / 8 - screenWidth / 40, paint); // text below level title paint.setTextSize(screenWidth / 30); paint.setColor(Color.WHITE); String tempHud = view.context.getResources().getString(R.string.Moves) + ":" + moves + "/" + board.bestMove + view.context.getResources().getString(R.string.best); int tempHudwidth = (int) paint.measureText(tempHud); int gap = (screenWidth - tempHudwidth) / 4; int chargap = (int) paint.measureText(" "); String spacegap = ""; for (int i = 0; i < gap; i += chargap) { spacegap += " "; } String HUD = ""; HUD = HUD + view.context.getResources().getString(R.string.moves) + ":" + moves + "/" + board.bestMove; // best user time String bestMove = view.savedState.getString(view.pack + "level" + view.currentLevel, "--"); HUD += spacegap + view.context.getResources().getString(R.string.best) + ":" + bestMove; int widthText = (int) paint.measureText(HUD); canvas.drawText( HUD, (Math.abs(screenWidth - widthText) / 2), board.gameBoard.top - screenWidth / 50, paint); // for hint text int Nem = (screenHeight - screenWidth) / 2 - (screenWidth / 35); canvas.drawText( "" + view.totalHintsLeft, view.buttonAction.mbHint.rec.right - screenWidth / 90, Nem + screenWidth + screenWidth / 20 + (screenWidth / 20) * 2 - (screenWidth / 20), paint); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.facebook_login_ui); // start login sub activity loghelper = FacebookLoginHelper.instance(this); handler = new LoginHandler(); facebook_info_span = (View) this.findViewById(R.id.facebook_info_span); facebook_info = (TextView) this.findViewById(R.id.facebook_info); facebook_info_span.setVisibility(View.VISIBLE); orm = SocialORM.instance(this); boolean forinvalidsession = getIntent().getBooleanExtra("forinvalidsession", false); if (forinvalidsession) { Log.d(TAG, "for invalid session issue=" + this); loghelper.clearSesion(); AccountListener.AccountManager.logout(); } // for UI email = (EditText) this.findViewById(R.id.facebook_login_email); email.setHint(R.string.facebook_email_address); pwd = (EditText) this.findViewById(R.id.facebook_login_pwd); pwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); pwd.setHint(R.string.facebook_password); login = (Button) this.findViewById(R.id.facebook_login_ok_button); sign_up = (Button) this.findViewById(R.id.facebook_login_sign_up_button); Paint p = login.getPaint(); float width1 = p.measureText(login.getText().toString()); p = null; p = sign_up.getPaint(); float width2 = p.measureText(sign_up.getText().toString()); int width = Math.round(Math.max(width1, width1)); width = width + 40; login.getLayoutParams().width = width; sign_up.getLayoutParams().width = width; p = null; login.setText(R.string.facebook_login_ok); sign_up.setText(R.string.facebook_login_sign_up); checkbox_sync_phonebook = (CheckBox) this.findViewById(R.id.checkbox_sync_phonebook); checkbox_sync_phonebook.setChecked(orm.isEnableSyncPhonebook()); checkbox_sync_phonebook.setOnCheckedChangeListener(checkedListener); login.setOnClickListener(loginClick); sign_up.setOnClickListener(signupClick); SocialORM.Account ac = orm.getFacebookAccount(); email.setText(ac.email); pwd.setText(ac.password); setTitle(R.string.menu_title_login); }
@Override public void onDraw(Canvas canvas, Rect bounds) { long now = System.currentTimeMillis(); mCalendar.setTimeInMillis(now); boolean is24Hour = DateFormat.is24HourFormat(FitDistanceWatchFaceService.this); // Draw the background. canvas.drawColor(BACKGROUND_COLOR); // Draw the hours. float x = mXOffset; String hourString; if (is24Hour) { hourString = formatTwoDigitNumber(mCalendar.get(Calendar.HOUR_OF_DAY)); } else { int hour = mCalendar.get(Calendar.HOUR); if (hour == 0) { hour = 12; } hourString = String.valueOf(hour); } canvas.drawText(hourString, x, mYOffset, mHourPaint); x += mHourPaint.measureText(hourString); // Draw first colon (between hour and minute). canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint); x += mColonWidth; // Draw the minutes. String minuteString = formatTwoDigitNumber(mCalendar.get(Calendar.MINUTE)); canvas.drawText(minuteString, x, mYOffset, mMinutePaint); x += mMinutePaint.measureText(minuteString); // In interactive mode, draw a second colon followed by the seconds. // Otherwise, if we're in 12-hour mode, draw AM/PM if (!isInAmbientMode()) { canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint); x += mColonWidth; canvas.drawText( formatTwoDigitNumber(mCalendar.get(Calendar.SECOND)), x, mYOffset, mSecondPaint); } else if (!is24Hour) { x += mColonWidth; canvas.drawText(getAmPmString(mCalendar.get(Calendar.AM_PM)), x, mYOffset, mAmPmPaint); } // Only render distance if there is no peek card, so they do not bleed into each other // in ambient mode. if (getPeekCardPosition().isEmpty()) { canvas.drawText( getString(R.string.fit_distance, mDistanceTotal), mXDistanceOffset, mYOffset + mLineHeight, mDistanceCountPaint); } }
/** * 根据字符串和画笔大小以及最大长度截取字符串 * * @param origStr * @param maxLength * @param paint * @return */ public String cutString(String origStr, int maxLength, Paint paint) { if (origStr != null) { if (paint.measureText(origStr) > maxLength) { for (int i = 1; i <= origStr.length(); i++) { String temp = origStr.substring(0, i); if (paint.measureText(temp) > maxLength) { return (String) origStr.subSequence(0, i - 1); } } } } return origStr; }
@Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); int mWidth = getWidth(); int mHeight = getHeight(); int cX = mWidth / 2; int cY = mHeight / 2; Paint paintCircle = new Paint(); paintCircle.setStyle(Paint.Style.STROKE); paintCircle.setStrokeWidth(5); canvas.drawCircle(cX, cY, mWidth / 2, paintCircle); Paint paintDegree = new Paint(); paintDegree.setTextSize(24); for (int i = 0; i < 12; i++) { if (i % 3 == 0) { paintDegree.setStrokeWidth(5); String degree = String.valueOf(i); canvas.drawLine( cX, mHeight / 2 - mWidth / 2, cX, mHeight / 2 - mWidth / 2 + 60, paintDegree); canvas.drawText( degree, cX - paintDegree.measureText(degree) / 2, mHeight / 2 - mWidth / 2 + 90, paintDegree); } else { paintDegree.setStrokeWidth(3); String degree = String.valueOf(i); canvas.drawLine( cX, mHeight / 2 - mWidth / 2, cX, mHeight / 2 - mWidth / 2 + 30, paintDegree); canvas.drawText( degree, cX - paintDegree.measureText(degree) / 2, mHeight / 2 - mWidth / 2 + 60, paintDegree); } canvas.rotate(30, cX, cY); } Paint paintHour = new Paint(); paintHour.setStrokeWidth(20); Paint paintMinute = new Paint(); paintMinute.setStrokeWidth(10); canvas.save(); canvas.translate(cX, cY); canvas.drawLine(0, 0, 100, 100, paintHour); canvas.drawLine(0, 0, 100, 200, paintMinute); canvas.restore(); }
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) { 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(); } }
private static String justifyOperation(String s, float width, Paint p) { float holder = (float) (COMPLEXITY * Math.random()); while (s.contains(Float.toString(holder))) holder = (float) (COMPLEXITY * Math.random()); String holder_string = Float.toString(holder); float lessThan = width; int timeOut = 100; int current = 0; while (p.measureText(s) < lessThan && current < timeOut) { s = s.replaceFirst(" ([^" + holder_string + "])", " " + holder_string + "$1"); lessThan = p.measureText(holder_string) + lessThan - p.measureText(" "); current++; } String cleaned = s.replaceAll(holder_string, " "); return cleaned; }
private static String wrap(String s, float width, Paint p) { String[] str = s.split("\\s"); // regex StringBuilder smb = new StringBuilder(); // save memory smb.append(SYSTEM_NEWLINE); for (int x = 0; x < str.length; x++) { float length = p.measureText(str[x]); String[] pieces = smb.toString().split(SYSTEM_NEWLINE); try { if (p.measureText(pieces[pieces.length - 1]) + length > width) smb.append(SYSTEM_NEWLINE); } catch (Exception e) { } smb.append(str[x] + " "); } return smb.toString().replaceFirst(SYSTEM_NEWLINE, ""); }
@Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); int height = getHeight(); int width = getWidth(); int interval = height / assort.length; for (int i = 0, length = assort.length; i < length; i++) { // 抗锯齿 paint.setAntiAlias(true); // 默认粗体 paint.setTypeface(Typeface.DEFAULT_BOLD); // 白色 paint.setColor(Color.WHITE); if (i == selectIndex) { // 被选择的字母改变颜色和粗体 paint.setColor(Color.parseColor("#3399ff")); paint.setFakeBoldText(true); paint.setTextSize(30); } // 计算字母的X坐标 float xPos = width / 2 - paint.measureText(assort[i]) / 2; // 计算字母的Y坐标 float yPos = interval * i + interval; canvas.drawText(assort[i], xPos, yPos, paint); paint.reset(); } }
public InfoExtImpl(float textSizeInPx) { mInfoPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mInfoPaint.setColor(0xFFCECECE); mInfoPaint.setTextSize(textSizeInPx); mInfoPaint.setTextAlign(Paint.Align.CENTER); mEllipseLength = (int) Math.ceil(mInfoPaint.measureText(ELLIPSE)); }
@Override public void onApplyWindowInsets(WindowInsets insets) { Log.d(TAG, "onApplyWindowInsets: " + (insets.isRound() ? "round" : "square")); super.onApplyWindowInsets(insets); // Load resources that have alternate values for round watches. Resources resources = FitDistanceWatchFaceService.this.getResources(); boolean isRound = insets.isRound(); mXOffset = resources.getDimension(isRound ? R.dimen.fit_x_offset_round : R.dimen.fit_x_offset); mXDistanceOffset = resources.getDimension( isRound ? R.dimen.fit_steps_or_distance_x_offset_round : R.dimen.fit_steps_or_distance_x_offset); float textSize = resources.getDimension(isRound ? R.dimen.fit_text_size_round : R.dimen.fit_text_size); float amPmSize = resources.getDimension(isRound ? R.dimen.fit_am_pm_size_round : R.dimen.fit_am_pm_size); mHourPaint.setTextSize(textSize); mMinutePaint.setTextSize(textSize); mSecondPaint.setTextSize(textSize); mAmPmPaint.setTextSize(amPmSize); mColonPaint.setTextSize(textSize); mDistanceCountPaint.setTextSize( resources.getDimension(R.dimen.fit_steps_or_distance_text_size)); mColonWidth = mColonPaint.measureText(COLON_STRING); }
/** * Calculate the bounds for a view's title * * @param index * @param paint * @return */ private RectF calcBounds(int index, Paint paint) { // Calculate the text bounds RectF bounds = new RectF(); bounds.right = paint.measureText(mTitleProvider.getTitle(index)); bounds.bottom = paint.descent() - paint.ascent(); return bounds; }
protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the rim canvas.drawArc(circleBounds, 360, 360, false, rimPaint); // Draw the bar if (isSpinning) { canvas.drawArc(circleBounds, progress - 90, barLength, false, barPaint); } else { canvas.drawArc(circleBounds, -90, progress, false, barPaint); } // Draw the inner circle canvas.drawCircle( (circleBounds.width() / 2) + rimWidth + paddingLeft, (circleBounds.height() / 2) + rimWidth + paddingTop, circleRadius, circlePaint); // Draw the text (attempts to center it horizontally and vertically) int offsetNum = 0; for (String s : splitText) { float offset = textPaint.measureText(s) / 2; canvas.drawText( s, this.getWidth() / 2 - offset, this.getHeight() / 2 + (textSize * (offsetNum)) - ((splitText.length - 1) * (textSize / 2)), textPaint); offsetNum++; } }
/** * Sets the icon for the marker. Can be changed at any time. * * @param icon if null, the default osmdroid marker is used. */ public void setIcon(Drawable icon) { if (ENABLE_TEXT_LABELS_WHEN_NO_IMAGE && icon == null && this.mTitle != null && this.mTitle.length() > 0) { Paint background = new Paint(); background.setColor(mTextLabelBackgroundColor); Paint p = new Paint(); p.setTextSize(mTextLabelFontSize); p.setColor(mTextLabelForegroundColor); p.setAntiAlias(true); p.setTypeface(Typeface.DEFAULT_BOLD); p.setTextAlign(Paint.Align.LEFT); int width = (int) (p.measureText(getTitle()) + 0.5f); float baseline = (int) (-p.ascent() + 0.5f); int height = (int) (baseline + p.descent() + 0.5f); Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(image); c.drawPaint(background); c.drawText(getTitle(), 0, baseline, p); mIcon = new BitmapDrawable(resource, image); } if (!ENABLE_TEXT_LABELS_WHEN_NO_IMAGE && icon != null) this.mIcon = icon; // there's still an edge case here, title label no defined, icon is null and textlabel is // enabled if (this.mIcon == null) mIcon = mDefaultIcon; }
private void Legends(List<String> legends_list, List<Integer> color_code_list) { textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextSize(20f); int left = (int) (graphwidth * 0.1); for (int i = 0; i < legends_list.size(); i++) { String label = legends_list.get(i); float text_width = textPaint.measureText(label, 0, label.length()); int color = color_code_list.get(i); if (!((graphwidth - legendLeft) > (text_width + 60))) { legendTop -= 60; legendLeft = left; } addLegends(canvas, color, legendTop, legendLeft, legendRight, legendBottom, label); legendLeft += ((int) text_width + 60); } }
private void measureItemHeight() { if (mItemRealHeight > 0) return; mPaint.setTextSize(mTextSize); mItemRealHeight = Math.max(Math.round(mPaint.measureText("9999", 0, 4)) + mPadding * 2, mItemHeight); }
// 根据字符大小以及运行的最大宽度判断是否将一个字符串分割成不超过最大长度的字符串数组,用于自动换行绘制文字 public ArrayList<String> splitStringByWidth(String str, float maxWidth, Paint paint) { if (str == null || "".equals(str)) { return null; } ArrayList<String> list = new ArrayList<String>(); int index = 0; int length = str.length(); for (int i = 0; i < length; i++) { String substr = str.substring(index, i + 1); float w = paint.measureText(substr); if (w > maxWidth) { if (i > 1) { list.add(str.substring(index, i)); } else { list.add(str.substring(0, 1)); } index = i; } } // 剩余的字符串 if (index < length) { list.add(str.substring(index)); } return list; }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取焦点改变背景色 int height = getHeight(); int width = getWidth(); int singleHeight = height / b.length; // 获取每一个字母的高度 for (int i = 0; i < b.length; i++) { paint.setColor(Color.rgb(33, 65, 98)); paint.setTypeface(Typeface.DEFAULT_BOLD); paint.setAntiAlias(true); paint.setTextSize(20 * (int) (displayMetrics != null ? (displayMetrics.density / 1.5) : 1)); // 选中的状态 if (i == choose) { paint.setColor(Color.parseColor("#3399ff")); paint.setFakeBoldText(true); } // x 坐标等于中间 - 字符串宽度的一半 float xPos = width / 2 - paint.measureText(b[i]) / 2; float yPos = singleHeight * i + singleHeight; canvas.drawText(b[i], xPos, yPos, paint); paint.reset(); } }
protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the inner circle canvas.drawArc(innerCircleBounds, 360, 360, false, circlePaint); // Draw the rim canvas.drawArc(circleBounds, 360, 360, false, rimPaint); canvas.drawArc(circleOuterContour, 360, 360, false, contourPaint); // canvas.drawArc(circleInnerContour, 360, 360, false, contourPaint); // Draw the bar if (isSpinning) { canvas.drawArc(circleBounds, progress - 90, barLength, false, barPaint); } else { canvas.drawArc(circleBounds, -90, progress, false, barPaint); } // Draw the text (attempts to center it horizontally and vertically) float textHeight = textPaint.descent() - textPaint.ascent(); float verticalTextOffset = (textHeight / 2) - textPaint.descent(); for (String line : splitText) { float horizontalTextOffset = textPaint.measureText(line) / 2; canvas.drawText( line, this.getWidth() / 2 - horizontalTextOffset, this.getHeight() / 2 + verticalTextOffset, textPaint); } if (isSpinning) { scheduleRedraw(); } }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int height = getHeight(); int width = getWidth(); // 每个字母对应的高度 int oneHeight = height / b.length; float xPos = 0; float yPos = 0; if (showBg) { canvas.drawColor(Color.TRANSPARENT); // canvas.drawColor(Color.parseColor("#40000000")); } // 开始画bar上的每个字母 for (int i = 0; i < b.length; i++) { if (i == chooseIndex) { barPaint.setColor(getResources().getColor(R.color.gray_deep)); } xPos = width / 2 - barPaint.measureText(b[i]) / 2; yPos = oneHeight * i + oneHeight; canvas.drawText(b[i], xPos, yPos, barPaint); } }
/** 重写这个方法 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取焦点改变背景颜色. int height = getHeight(); // 获取对应高度 1596 samsung s4 int width = getWidth(); // 获取对应宽度 int singleHeight = height / b.length; // 获取每一个字母的高度 for (int i = 0; i < b.length; i++) { paint.setColor(Color.rgb(33, 65, 98)); // 右边字母导航条的颜色 // paint.setColor(Color.WHITE); paint.setTypeface(Typeface.DEFAULT_BOLD); paint.setAntiAlias(true); paint.setTextSize(height / 320 * 10); // 根据屏幕分辨率设置字体大小 // 选中的状态 if (i == choose) { paint.setColor(Color.parseColor("#3399ff")); paint.setFakeBoldText(true); } // x坐标等于中间-字符串宽度的一半. float xPos = width / 2 - paint.measureText(b[i]) / 2; float yPos = singleHeight * i + singleHeight; canvas.drawText(b[i], xPos, yPos, paint); paint.reset(); // 重置画笔 } }
private LayoutInfo layout() { LayoutInfo info = new LayoutInfo(); info.labelHeight = labelPaint.descent() - labelPaint.ascent(); float maxMarkerSize = Float.MIN_VALUE; float maxLength = Float.MIN_VALUE; for (Entry entry : entryList) { float length = labelPaint.measureText(entry.label); if (maxLength < length) maxLength = length; float markerSize = entry.painter.getDrawConfig().getMarkerSize(); if (markerSize > maxMarkerSize) maxMarkerSize = markerSize; } info.markerWidth = maxMarkerSize; info.frame.left = 0; info.frame.top = 0; info.frame.right = 2 * info.margin + info.markerWidth + info.markerXSpacing + maxLength + 2 * info.markerLineSpace; info.frame.bottom = 2 * info.margin + entryList.size() * (info.labelHeight + info.labelSpacing); return info; }