I'm new to work with Canvas in Android. I have the following code:
textGreetingsPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textGreetingsPaint.setARGB(255, 0, 0, 0);
textGreetingsPaint.setTextAlign(Paint.Align.CENTER);
textGreetingsPaint.setTypeface(Typeface.DEFAULT_BOLD);
textSubGreetingsPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textSubGreetingsPaint.setARGB(255, 0, 0, 0);
textSubGreetingsPaint.setTextAlign(Paint.Align.CENTER);
textSubGreetingsPaint.setTypeface(Typeface.DEFAULT_BOLD);
final float startText = (canvas.getWidth() / 2);
final float endText = ((canvas.getHeight() / 2) - ((textGreetingsPaint.descent() + textGreetingsPaint.ascent()) / 2));
final float endSubText = endText + 150;
textGreetingsPaint.setTextSize(determineMaxTextSize("Good night,", (float) (getWidth() / 1.2)));
textSubGreetingsPaint.setTextSize(determineMaxTextSize("how was your day?", (float) (getWidth() / 1.2)));
canvas.drawText("Good night,", startText, endText, textGreetingsPaint);
canvas.drawText("how was your day?", startText, endSubText, textSubGreetingsPaint);
private int determineMaxTextSize(String str, float maxWidth) {
int size = 0;
Paint paint = new Paint();
do {
paint.setTextSize(++size);
} while (paint.measureText(str) < maxWidth);
return size;
}
It basically insets two texts in the center of the canvas:
Good night,
how was your day?
I have the following issue - currently I set the endSubText to be endText + 150, meaning I will have the Good night message in the center of the screen and the how was your day? message under it, meaning I will have something like (note the empty rows):
>
>
> Good night,
>
> how was your day?
>
I want both of the messages to be in the center of the canvas, something like:
>
> Good night,
>
> how was your day?
>
Also, I set endSubText to be endText + 150 with const 150 but it could be different in each screen. How to keep a valid margin between those two texts?
To sum up the questions:
How to set the texts in the center of the canvas?
How to keep valid margin between texts?
Related
I learned about how to create an OTP from drawable using canvas. OTP screen
But I want to have a box instead of a plane lines at the bottom, and I want to have the text in the middle of the box, instead of 8 dp above the line. I made a few modification like adding a rectf and drawing using canvas. It was easy. But It will not be responsive on all the screens.
#Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
int availableWidth = getWidth() - getPaddingRight() - getPaddingLeft();
int availableHeight= getHeight()-getPaddingTop()-getPaddingBottom();
if (mSpace < 0) {
mCharSize = (availableWidth / (mNumChars * 2 - 1));
} else {
mCharSize = (availableWidth - (mSpace * (mNumChars - 1))) / mNumChars;
}
int startX = getPaddingLeft();
int bottom = getHeight() - getPaddingBottom();
//Text Width
Editable text = getText();
int textLength = text.length();
float[] textWidths = new float[textLength];
getPaint().getTextWidths(getText(), 0, textLength, textWidths);
Paint mPaint = new Paint();
RectF rectF;
int cornerRadius = 15;
for (int i = 0; i < mNumChars; i++) {
mPaint.setColor(getResources().getColor(R.color.colorViews));
mPaint.setAlpha(70);
mPaint.setStyle(Paint.Style.FILL);
rectF = new RectF(startX, availableHeight, startX + (int) mCharSize, bottom);
canvas.drawRoundRect(rectF,cornerRadius,cornerRadius,mPaint);
// canvas.drawLine(startX, bottom, startX + mCharSize, bottom, mPaint);
if (getText().length() > i) {
float middle = startX + mCharSize / 2;
//y= bottom-mLineSpacing
canvas.drawText(text, i, i + 1, middle - textWidths[0] / 2, bottom-mLineSpacing, getPaint());
}
if (mSpace < 0) {
startX += mCharSize * 2;
} else {
startX += mCharSize + mSpace;
}
}
}
And my xml file looks something like this
<com.example.android.EditTextOTP
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:cursorVisible="false"
android:digits="1234567890"
android:inputType="number"
android:maxLength="4"
android:textIsSelectable="false"
android:textSize="20sp"
android:background="#null"
android:paddingStart="40dp"
android:paddingEnd="40dp"
android:paddingTop="60dp"
app:layout_constraintTop_toBottomOf="#id/tv_otp_text"
app:layout_constraintStart_toStartOf="#id/gl_inside_bg"
app:layout_constraintEnd_toEndOf="#id/gl_vertical_end"
android:id="#+id/et_otp_box"
>
</com.example.android.EditTextOTP>
The above way works fine but I want to place the number as I type in the center of the BOX. not roughly on the top of the BOX. How can I improve this?
How can I draw Path with fading (opacity or thicknes) line? Something like this.
I know there is LinearGradient shader for Paint, but it won't bend along the Path.
One possible solution might be to get points along the Path and just draw it by myself through the segments`. But I coouldn't find any method for that either.
I came up with the following code. The mos important thing is PathMeasure's getPosTan() method.
if (getGesturePath() != null) {
final short steps = 150;
final byte stepDistance = 5;
final byte maxTrailRadius = 15;
pathMeasure.setPath(getGesturePath(), false);
final float pathLength = pathMeasure.getLength();
for (short i = 1; i <= steps; i++) {
final float distance = pathLength - i * stepDistance;
if (distance >= 0) {
final float trailRadius = maxTrailRadius * (1 - (float) i / steps);
pathMeasure.getPosTan(distance, pathPos, null);
final float x = pathPos[0] + RandomUtils.nextFloat(0, 2 * trailRadius) - trailRadius;
final float y = pathPos[1] + RandomUtils.nextFloat(0, 2 * trailRadius) - trailRadius;
paint.setShader(new RadialGradient(
x,
y,
trailRadius > 0 ? trailRadius : Float.MIN_VALUE,
ColorUtils.setAlphaComponent(Color.GREEN, random.nextInt(0xff)),
Color.TRANSPARENT,
Shader.TileMode.CLAMP
));
canvas.drawCircle(x, y, trailRadius, paint);
}
}
}
Good day.I am creating a siri like wave for android and i encounter an big issue.I need the wave to be in 4 colors.Lets assume i only have one single line which is drawing on the screen accordingly to the voice decibels.Anyway i am able to do it but no way i am able to give 4 different colors for same path.Assume it is 1 single path which moves from screen start to screen end,i need that line to have 4 different colors,mainly i had to divide the path into 4 parts and draw the color for each parts,but neither google,nor any other source give me anything (not even found anything similar to what i want).
Meanwhile i am posting the code where actually i am drawing the lines.
for (int l = 0; l < mWaveCount; ++l) {
float midH = height / 2.0f;
float midW = width / 2.0f;
float maxAmplitude = midH / 2f - 4.0f;
float progress = 1.0f - l * 1.0f / mWaveCount;
float normalAmplitude = (1.5f * progress - 0.5f) * mAmplitude;
float multiplier = (float) Math.min(1.0, (progress / 3.0f * 2.0f) + (1.0f / 3.0f));
if (l != 0) {
mSecondaryPaint.setAlpha((int) (multiplier * 255));
}
mPath.reset();
for (int x = 0; x < width + mDensity; x += mDensity) {
float scaling = 1f - (float) Math.pow(1 / midW * (x - midW), 2);
float y = scaling * maxAmplitude * normalAmplitude * (float) Math.sin(
180 * x * mFrequency / (width * Math.PI) + mPhase) + midH;
// canvas.drawPoint(x, y, l == 0 ? mPrimaryPaint : mSecondaryPaint);
//
// canvas.drawLine(x, y, x, 2*midH - y, mSecondaryPaint);
if (x == 0) {
mPath.moveTo(x, y);
} else {
mPath.lineTo(x, y);
// final float x2 = (x + mLastX) / 2;
// final float y2 = (y + mLastY) / 2;
// mPath.quadTo(x2, y2, x, y);
}
mLastX = x;
mLastY = y;
}
if (l == 0) {
canvas.drawPath(mPath, mPrimaryPaint);
} else {
canvas.drawPath(mPath, mSecondaryPaint);
}
}
I tried to change color on if (l == 0) {
canvas.drawPath(mPath, mPrimaryPaint);
} but if i change it here,no result at all,either the line is separate and not moving at all,but it should,either the color is not applied,propably because i am doing it in loop as i had to and everytime the last color is picked to draw.Anyway can you help me out?Even an small reference is gold for me because really there is nothing at all in the internet.
Anyway even though Matt Horst answer fully correct,i found the simplest and easiest solution...i never thought it would be so easy.Anyway if in world there is someone who need to make an path divided into multiple colors,here is what you can do
int[] rainbow = getRainbowColors();
Shader shader = new LinearGradient(0, 0, 0, width, rainbow,
null, Shader.TileMode.REPEAT);
Matrix matrix = new Matrix();
matrix.setRotate(90);
shader.setLocalMatrix(matrix);
mPrimaryPaint.setShader(shader);
Where getRainbowColors() is an array of colors you wish your line to have and width is the length of the path so the Shader knows how to draw the colors in right way to fit the length of path.Anyway .....easy isnt it?and pretty purged me a lot to get into this simple point.Nowhere in internet you could find only if you are looking for something completelly different,than you might come across this.
It seems to me like you could set up one paint for each section, each with a different color. Then set up one path for each section too. Then as you draw across the screen, wherever the changeover point is between sections, start drawing with the new path. And make sure first to use moveTo() on the new path so it starts off where the old one left off.
For my solution, I tried changing the color of the linePaint in the onDraw Call. But it was drawing a single color.
So i used two different paints for two different colors and draw path on the canvas.
And it worked. Hope it helps someone out there.
i have problem with detection road lanes with my phone.
i wrote some code for road lanes detection, but him not working for me.
From camera get modifications from normal view to BGR colors and try use GausianBlur and Canny, but i think i not good draw lanes for detection.
Maybe some people have another idea how detection road lanes with OpenCV?
Mat mYuv = new Mat(height + height / 2, width, CvType.CV_8UC1);
Mat mRgba = new Mat(height + height / 2, width, CvType.CV_8UC1);
Mat thresholdImage = new Mat(height + height / 2, width, CvType.CV_8UC1);
mYuv.put(0, 0, data);
Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV420p2BGR, 4);
//convert to grayscale
Imgproc.cvtColor(mRgba, thresholdImage, Imgproc.COLOR_mRGBA2RGBA, 4);
// Perform a Gaussian blur (convolving in 5x5 Gaussian) & detect edges
Imgproc.GaussianBlur(mRgba, mRgba, new Size(5,5), 2.2, 2);
Imgproc.Canny(mRgba, thresholdImage, VActivity.CANNY_MIN_TRESHOLD, VActivity.CANNY_MAX_THRESHOLD);
Mat lines = new Mat();
double rho = 1;
double theta = Math.PI/180;
int threshold = 50;
//do Hough transform to find lanes
Imgproc.HoughLinesP(thresholdImage, lines, rho, theta, threshold, VActivity.HOUGH_MIN_LINE_LENGTH, VActivity.HOUGH_MAX_LINE_GAP);
for (int x = 0; x < lines.cols() && x < 1; x++){
double[] vec = lines.get(0, x);
double x1 = vec[0],
y1 = vec[1],
x2 = vec[2],
y2 = vec[3];
Point start = new Point(x1, y1);
Point end = new Point(x2, y2);
Core.line(mRgba, start, end, new Scalar(255, 0, 0), 3);
}
This approach is fine and I've done something similar, not for road line detection but I did notice that it could be used for that purpose. Some comments:
Not sure why you do:
Imgproc.cvtColor(mRgba, thresholdImage, Imgproc.COLOR_mRGBA2RGBA, 4);
as 1. the comment say convert to greyscale, which is a single channel and 2. thresholdImage will get overwritten with the call to Canny later. You just need to dimension thresholdImage with:
thresholdImage = new Mat(mRgba.size(), CvType.CV_8UC1);
What are your parameter values to the call to Canny? I played about with mine considerably and ended up with values like: threshold1 = 441, threshold2 = 160, aperture = 3.
Likewise Imgproc.HoughLinesP: I use Imgproc.HoughLines rather than Imgproc.HoughLinesP with parameters: threshold = 80, minLen = 30, maxLen = 10.
Also have a look at:
for (int x = 0; x < lines.cols() && x < 1; x++){
&& x < 1 means you will only take the first line that the call to HoughLinesP returns. I'd suggest you remove this and use some other criteria to reduce the number of lines; for example, I was interesting in only horizontal and vertical lines so I used atan2 to calculate line angles and exclude those that deviate too much.
UPDATE
Here is how I get the angle of a line. Assuming coordinates of one point is (x1,y1) and the other (x2, y2) then to get the angle:
double lineAngle = Math.atan2(y2 - y1, x2 - x1);
this should return an angle in radians between -PI/2 and PI/2
With regard Canny parameters then I would experiment - I set up onTouch so that I could adjust the threshold values by touching certain parts of the screen to see the effects in realtime. Note that aperture is rather disappointing parameter: it seems to only like odd values 3, 5 and 7 and 3 is the best that I've found.
Something like in the onTouch method:
int w = mRgba.width();
int h = mRgba.height();
float x = event.getX();
float y = event.getY();
if ((x < w / 3) && (y < h / 2)) t1 += 20;
if ((x < w / 3) && (y >= h / 2)) t1 -= 20;
if ((x > 2 * w / 3) && (y < h / 2)) t2 += 20;
if ((x > 2 * w / 3) && (y >= h / 2)) t2 -= 20;
t1 and t2 being the threshold values passed to the Canny call.
Hi I'm trying to make a square 8x8 grid on a canvas. I've managed to make a grid, but it turns out to be rectangular, but for the game I'm making it needs to be square. How do I change my code to make it a square grid scaled to the phone.
float testWidth = (getWidth() - 16f) / 9f;
float testHeight = (getHeight() - 16f) / 9f;
for (int i = 0; i < 9; i++) {
canvas.drawLine(padding + testWidth* i, padding, padding
+ testWidth * i, testHeight* 8+padding, dark);
canvas.drawLine(padding, padding+testHeight* i, testWidth* 8
+ padding, padding+testHeight* i, dark);
}
EDIT: I can now make a square grid, but I don't know how to center the grid into the middle of the phone
You'll want to take the shortest of the two (Width or Height) and use that to build the grid upon. (So your grid can fit on the screen)
Something like...:
float gridSide = 0;
if (getWidth() > getHeight()) {
gridSide = getHeight();
}
else {
gridSide = getWidth();
}
Simpler logic provided by appsroxcom:
float gridSide = Math.min(testWidth(), testHeight());
Use gridSide as the total length and total width of the grid