Center Text on Watch

2019-05-28 13:46发布

I've been trying multiple ways to center 3 lines of text on a watch and can't seem to figure it out. The new watch face services require you to paint to a canvas. I initialize the text offset by grabbing the length of text of each line and dividing by 2.

mXDateOffset = mTextDateColorPaint.measureText("May 21, 2015") /2;
mXTimeOffset = mTextTimeColorPaint.measureText("12:00:00")/2;
mXBatteryOffset = mTextBatteryColorPaint.measureText("99%") /2 ;

Then when I set the text and paint elements to the canvas I find the center of the rectangle(screen) minus the screen to find the start position of the text.

canvas.drawText( timeText, bounds.centerX() - mXTimeOffset, 40.0f, mTextTimeColorPaint );
canvas.drawText( date, bounds.centerX() - mXDateOffset, 90.0f, mTextDateColorPaint);
canvas.drawText( mBatteryLevel, bounds.centerX() - mXBatteryOffset, 130.0f, mTextBatteryColorPaint );

What I get is this...

enter image description here

Not sure what else to do.

1条回答
女痞
2楼-- · 2019-05-28 14:39

There is alot that went into this answer here is what I came up with having to access the onDraw methods:

in onCreate() set the offsets

mYTimeOffset = getResources().getDimension( R.dimen.y_offset );
mYDateOffset = getResources().getDimension( R.dimen.y_date_offset );
mYBatteryOffset = getResources().getDimension( R.dimen.y_battery_offset );

then call the drawtime and set the canvas parameters

    private void drawTimeText(Canvas canvas, Rect bounds) {
        String timeText = getHourString() + ":" + String.format( "%02d", mDisplayTime.minute );
        if( isInAmbientMode() || mIsInMuteMode ) {
            timeText += ( mDisplayTime.hour < 12 ) ? "AM" : "PM";
        } else {
            timeText += String.format( ":%02d", mDisplayTime.second);
        }

        String date = new SimpleDateFormat(DATE_FORMAT_DISPLAYED).format(Calendar.getInstance().getTime());
        canvas.drawText( timeText, bounds.centerX() - (mTextTimeColorPaint.measureText(timeText))/2, mYTimeOffset, mTextTimeColorPaint );
        canvas.drawText( date, bounds.centerX() - (mTextDateColorPaint.measureText(date))/2, mYDateOffset, mTextDateColorPaint);
        if (mBatteryLevel != null)
        canvas.drawText( mBatteryLevel, bounds.centerX() - (mTextBatteryColorPaint.measureText(mBatteryLevel))/2, mYBatteryOffset, mTextBatteryColorPaint );
    }
查看更多
登录 后发表回答