How to draw a custom background - android

I have to design a triangle and display some text inside it with an angle of 45, below that I have to put a text view outside the boundaries of the triangle to display some other text. It is like a banner. However when I use a relative layout and put a triangular background, it still acts as a rectangle, obscuring my Text view. Below is the code I use:
<RelativeLayout
android:id="#+id/relative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/image_sticker" >
<com.example.AngledTextView
android:id="#+id/textViewx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:rotation="52"
android:textColor="#FFFFFF" />
</RelativeLayout>
My AngledTextView Class:
public class AngledTextView extends TextView {
private int mWidth;
private int mHeight;
public AngledTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
/*Paint textPaint = new Paint();
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.rotate(45, xPos,yPos); */
super.onDraw(canvas);
canvas.restore();
}
}
Problem:
Any hints or links to suggested tutorials will be highly appreciated :)

i've done similar stuff recently. Here are some tips i've used:
Create customView class.
Init at least one Paint (semitransparent, fill) and one Path on your init method. It should be called from constructors.
On your onDraw method customize path. For example:
mPath = new Path();
mPath.moveTo(.0f, this.getHeight());
mPath.lineTo(this.getWidth(), this.getHeight());
mPath.lineTo(this.getWidth(),0.25f*this.getHeight());
mPath.lineTo(.0f, .0f);
mPath.lineTo(.0f, this.getHeight());
This will make a Path similar to a trapezoid. Just customize your points to make a triangle. Then call
canvas.clipPath(mPath);
canvas.drawPath(mPath,mPaint);
With these points, you will draw your triangle. You could pass a String to your init method and call drawText before drawing the path:
canvas.drawText(str, xTit, yTit, mPaintTit);
I hope this will help =)

In your regular textview use rotate animation like.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:rotation="45"
android:text="#string/hello_world" />

Your implementation could inherit from Drawable and implement getTransparentRegion()
Next, use this drawable as background on a view that is drawn on top of your TextView (probably by having both as childs inside a FrameView)

i have some link for crate triangle background as below
link1
link2
link3
i hope it helpful for you

Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless the structure (the original coordinates) of the shapes you use in your program change during the course of execution, you should initialize them in the onSurfaceCreated() method of your renderer for memory and processing efficiency.
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
...
// initialize a triangle
mTriangle = new Triangle();
// initialize a square
mSquare = new Square();
}
Example
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
public class Slice extends LinearLayout {
final static String TAG = "Slice";
Paint mPaint;
Path mPath;
public enum Direction {
NORTH, SOUTH, EAST, WEST;
}
public Slice(Context context) {
super(context);
Create(context);
}
public Slice(Context context, AttributeSet attrs) {
super(context, attrs);
Create(context);
}
private void Create(Context context) {
Log.i(TAG, "Creating ...");
mPaint = new Paint();
mPaint.setStyle(Style.FILL);
mPaint.setColor(Color.RED);
Point point = new Point();
point.x = 80;
point.y = 80;
mPath = Calculate(point, 70, Direction.SOUTH);
}
#Override
protected void onDraw(Canvas canvas) {
Log.i(TAG, "Drawing ...");
canvas.drawPath(mPath, mPaint);
}
private Path Calculate(Point p1, int width, Direction direction) {
Log.i(TAG, "Calculating ...");
Point p2 = null, p3 = null;
if (direction == Direction.NORTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y - width);
} else if (direction == Direction.SOUTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y + width);
} else if (direction == Direction.EAST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x - width, p1.y + (width / 2));
} else if (direction == Direction.WEST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x + width, p1.y + (width / 2));
}
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
return path;
}
}

Related

diamond shape in android studio

I'm having trouble using a path to create a diamond shape on Android studio. It looks like I have a little more than half of the diamond, but I don't know what I am doing wrong and why the rest of it isn't printing out. I've been trying to change my code for hours and nothing is working. Could anyone please point out what I am doing wrong? Here is my code so far:
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.shapes.Shape;
public class Diamond extends Shape {
private int strokeWidth;
private final int fillColor;
private int strokeColor;
private Path path;
private Paint strokePaint;
private Paint fillPaint;
public Diamond(int strokeWidth, int fillColor, int strokeColor) {
this.strokeWidth = strokeWidth;
this.fillColor = fillColor;
this.strokeColor = strokeColor;
this.strokePaint = new Paint();
this.strokePaint.setStyle(Paint.Style.STROKE);
this.strokePaint.setStrokeWidth(strokeWidth);
this.fillPaint = new Paint();
this.fillPaint.setStyle(Paint.Style.FILL);
this.fillPaint.setColor(fillColor);
}
#Override
public void draw(Canvas canvas, Paint paint) {
canvas.drawPath(path, fillPaint);
canvas.drawPath(path, strokePaint);
}
#Override
protected void onResize(float width, float height) {
super.onResize(width, height);
path = new Path();
path.moveTo(width/2, 0);
path.lineTo(width, height);
path.lineTo(width/2, height*4);
path.lineTo(0, height);
path.close();
}
}
I think you should just need to change path.lineTo(width/2, height*4); to instead multiply the height by 2 as in path.lineTo(width/2, height*2);, using 4 makes the bottom half skewed longer than the top. There's also an example on this page drawing a rhombus which you can modify to draw a diamond by using the full width like:
public void drawRhombus(Canvas canvas, Paint paint, int x, int y, int width) {
int halfWidth = width / 2;
Path path = new Path();
path.moveTo(x, y + width); // Top
path.lineTo(x - halfWidth, y); // Left
path.lineTo(x, y - width); // Bottom
path.lineTo(x + halfWidth, y); // Right
path.lineTo(x, y + width); // Back to Top
path.close();
canvas.drawPath(path, paint);
}

Draw round corners on top left top right bottom left bottom right using Path and RectF in Android

By making a custom ImageView and override the onDraw method with the following will make the ImageView to have rounded corners. Reference
#Override
protected void onDraw(Canvas canvas) {
float radius = getContext().getResources().getDimension(R.dimen.round_corner_radius);
Path path = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
path.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(path);
super.onDraw(canvas);
}
How can I selectively make the round corners instead of making all four corners round. For example, only making the top left and top right corners round and leave the bottom corners intact. Here is a solution to do to through Bitmap. I am looking for doing it in this onDraw method and only using Path and RectF.
There is a Path#addRoundRect() overload that takes a float array of eight values wherein we can specify the x- and y-radius for each of the four corners. These values are in [x, y] pairs, starting at the top-left corner, and going clockwise around the rest. For those corners we want rounded, we set both values of the pair to the radius value, and leave them at zero for those we don't.
As an illustrative example, a simple method that will return a Path that can be used in your snippet:
private Path getPath(float radius, boolean topLeft, boolean topRight,
boolean bottomRight, boolean bottomLeft) {
final Path path = new Path();
final float[] radii = new float[8];
if (topLeft) {
radii[0] = radius;
radii[1] = radius;
}
if (topRight) {
radii[2] = radius;
radii[3] = radius;
}
if (bottomRight) {
radii[4] = radius;
radii[5] = radius;
}
if (bottomLeft) {
radii[6] = radius;
radii[7] = radius;
}
path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()),
radii, Path.Direction.CW);
return path;
}
Per your example description, rounding the top-left and top-right corners:
#Override
protected void onDraw(Canvas canvas) {
float radius = getContext().getResources().getDimension(R.dimen.round_corner_radius);
Path path = getPath(radius, true, true, false, false);
canvas.clipPath(path);
super.onDraw(canvas);
}
As always, I would recommend keeping the onDraw() method as tight as possible, moving anything that doesn't absolutely have to be there elsewhere. The resource value for the radius, for instance, could be retrieved in the constructor, and kept in a field. Furthermore, the Path could be constructed only when necessary; i.e., when the View's size changes, or when the radius or chosen corners change.
Since I put together a simple custom ImageView to test this, I'll include it here, as it demonstrates the above points. This custom View also offers XML attributes that allow the corner radius and the rounded corners to be set in your layout.
public class RoundishImageView extends ImageView {
public static final int CORNER_NONE = 0;
public static final int CORNER_TOP_LEFT = 1;
public static final int CORNER_TOP_RIGHT = 2;
public static final int CORNER_BOTTOM_RIGHT = 4;
public static final int CORNER_BOTTOM_LEFT = 8;
public static final int CORNER_ALL = 15;
private static final int[] CORNERS = {CORNER_TOP_LEFT,
CORNER_TOP_RIGHT,
CORNER_BOTTOM_RIGHT,
CORNER_BOTTOM_LEFT};
private final Path path = new Path();
private int cornerRadius;
private int roundedCorners;
public RoundishImageView(Context context) {
this(context, null);
}
public RoundishImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundishImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundishImageView);
cornerRadius = a.getDimensionPixelSize(R.styleable.RoundishImageView_cornerRadius, 0);
roundedCorners = a.getInt(R.styleable.RoundishImageView_roundedCorners, CORNER_NONE);
a.recycle();
}
public void setCornerRadius(int radius) {
if (cornerRadius != radius) {
cornerRadius = radius;
setPath();
invalidate();
}
}
public int getCornerRadius() {
return cornerRadius;
}
public void setRoundedCorners(int corners) {
if (roundedCorners != corners) {
roundedCorners = corners;
setPath();
invalidate();
}
}
public boolean isCornerRounded(int corner) {
return (roundedCorners & corner) == corner;
}
#Override
protected void onDraw(Canvas canvas) {
if (!path.isEmpty()) {
canvas.clipPath(path);
}
super.onDraw(canvas);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setPath();
}
private void setPath() {
path.rewind();
if (cornerRadius >= 1f && roundedCorners != CORNER_NONE) {
final float[] radii = new float[8];
for (int i = 0; i < 4; i++) {
if (isCornerRounded(CORNERS[i])) {
radii[2 * i] = cornerRadius;
radii[2 * i + 1] = cornerRadius;
}
}
path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()),
radii, Path.Direction.CW);
}
}
}
For the XML attributes to work, the following needs to be in your <resources>, which you can do by putting this file in your project's res/values/ folder, or adding to the one that might already be there.
attrs.xml
<resources>
<declare-styleable name="RoundishImageView">
<attr name="cornerRadius" format="dimension" />
<attr name="roundedCorners">
<flag name="topLeft" value="1" />
<flag name="topRight" value="2" />
<flag name="bottomRight" value="4" />
<flag name="bottomLeft" value="8" />
<flag name="all" value="15" />
</attr>
</declare-styleable>
</resources>
The cornerRadius is a dimension attribute, and should be specified as a dp or px value. The roundedCorners is a flag attribute, and multiple corners can be chosen using the pipe character, |. For example:
<com.mycompany.myapp.RoundishImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/riv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/magritte"
app:cornerRadius="#dimen/round_corner_radius"
app:roundedCorners="topLeft|topRight" />
I also spent a half-day to solve the problem; the key point here is how to use mPath.arcTo make a corner. The basic knowledge is E direction is 0 degree, then the second param means which degree start; the third param means how many degrees to show.
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
public class RectangleConerView extends View {
private Path mPath;
private Paint mPaint;
private PathMeasure mPathMeasure;
private float mAnimatorValue;
private Path mDst;
private float mLength;
private float left = 300;
private float top = 200;
private float width = 800;
private float height = 300;
private float checkWidth = 100;
private float checkHeight = 60;
private float cornerRadius = 30;
public RectangleConerView(Context context) {
super(context);
}
public RectangleConerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public RectangleConerView(Context context, AttributeSet attrs)
{
super(context, attrs);
mPathMeasure = new PathMeasure();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPath = new Path();
mPath.moveTo(left + width, top + checkHeight/2);
//bottom-right
mPath.lineTo(left + width, top + height - cornerRadius);
mPath.arcTo(new RectF(left + width-cornerRadius, top + height - cornerRadius, left + width, top + height), 0, 90); //start degree is E direct, then CW 90 degree, which is the bottom-right corner.
//bottom-left
mPath.lineTo(left + cornerRadius, top + height);
mPath.arcTo(new RectF(left, top + height - cornerRadius, left + cornerRadius, top + height), 90, 90);//start degree is the S, then CW 90 degree, which is the bottom-left corner.
//top-left
mPath.lineTo(left, top + cornerRadius);
mPath.arcTo(new RectF(left, top, left + cornerRadius, top + cornerRadius), 180, 90);//start degree W
//top-right
mPath.lineTo(left + width - checkWidth/2, top);
mPathMeasure.setPath(mPath, false);
mLength = mPathMeasure.getLength();
mDst = new Path();
final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mAnimatorValue = (float) valueAnimator.getAnimatedValue();
invalidate();
}
});
valueAnimator.setDuration(1000);
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
valueAnimator.setInterpolator(new DecelerateInterpolator());
valueAnimator.start();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mDst.reset();
// 硬件加速的BUG
mDst.lineTo(0,0);
float stop = mLength * mAnimatorValue;
mPathMeasure.getSegment(0, stop, mDst, true);
canvas.drawPath(mDst, mPaint);
}
}

How to change the color of the side view of the star in android?

To see the below image,
Masking star
And the code is,
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Region;
import android.view.View;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
/**
* Created by chozarajan.pandiyarajan on 11/3/2015.
*/
public class SfRatingItem extends View {
private int fillColor, minDim, topXPoint, topYPoint;
private double bigHypot, bigA, bigB, littleHypot, littleA, littleB, value;
private Paint starPaint;
private Path path;
private Bitmap starBitmap;
private Bitmap backBitmap;
public SfRatingItem(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public SfRatingItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
public SfRatingItem(Context context) {
super(context);
initialize();
this.setBackgroundColor(Color.GREEN);
}
#Override
protected void onDraw(Canvas canvas) {
initialDraw();
Paint q = new Paint(Paint.ANTI_ALIAS_FLAG);
//canvas.saveLayer(0,0,canvas.getWidth(),canvas.getHeight(),q); // expensive call, instead set a hardware layer
setLayerType(LAYER_TYPE_HARDWARE, q);
canvas.drawBitmap(backBitmap, 0, 0, q);
q.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(starBitmap, 0, 0, q);
q.setXfermode(null);
Paint p=new Paint();
p.setColor(Color.RED);
p.setStyle(Paint.Style.STROKE);
p.setAntiAlias(true);
canvas.drawPath(path,p);
}
private void initialDraw() {
starPaint.setStyle(Paint.Style.FILL_AND_STROKE);
starPaint.setAntiAlias(true);
minDim = Math.min(this.getWidth() - this.getPaddingLeft() - this.getPaddingRight(), this.getHeight() - this.getPaddingTop() - this.getPaddingBottom());
bigHypot = (minDim / Math.cos(Math.toRadians(18)));
bigB = minDim;
bigA = Math.tan(Math.toRadians(18)) * bigB;
littleHypot = bigHypot / (2 + Math.cos(Math.toRadians(72)) + Math.cos(Math.toRadians(72)));
littleA = Math.cos(Math.toRadians(72)) * littleHypot;
littleB = Math.sin(Math.toRadians(72)) * littleHypot;
topXPoint = (this.getWidth() - this.getPaddingLeft() - this.getPaddingRight()) / 2;
topYPoint = this.getPaddingTop();
path.moveTo(topXPoint, topYPoint);
path.lineTo((int) (topXPoint + bigA), (int) (topYPoint + bigB));
path.lineTo((int) (topXPoint - littleA - littleB), (int) (topYPoint + littleB));
path.lineTo((int) (topXPoint + littleA + littleB), (int) (topYPoint + littleB));
path.lineTo((int) (topXPoint - bigA), (int) (topYPoint + bigB));
path.lineTo(topXPoint, topYPoint);
path.close();
RectF bounds = new RectF();
path.computeBounds(bounds, true);
// Draw the background rectangle in a bitmap
starPaint.setColor(Color.RED);
backBitmap = Bitmap.createBitmap((int) bounds.width(), (int) bounds.height(), Bitmap.Config.ARGB_8888);
Canvas backCanvas = new Canvas(backBitmap);
final Rect backRect = new Rect(0, 0, 200, backBitmap.getHeight());
// Draw the STAR mask in a bitmap
starBitmap = Bitmap.createBitmap((int) bounds.width(), (int) bounds.height(), Bitmap.Config.ARGB_8888);
Canvas starCanvas = new Canvas(starBitmap);
starPaint.setColor(Color.RED);
starCanvas.drawPath(path, starPaint);
backCanvas.drawRect(backRect, starPaint);
}
private void initialize() {
starPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
path = new Path();
}
}
Please to see the above mentioned image.
In this code i am set the background of the window is green color.
And my question is, why the outside of the star is showing black color? and how to change that color?
The reason this is not working is because the Hardware acceleration might be turned off and you need to turn it on. Refer this: http://developer.android.com/guide/topics/graphics/hardware-accel.html
But if you are not planning to do this via Hardware Acceleration, then use
canvas.saveLayer(0,0,canvas.getWidth(),canvas.getHeight(),q);
instead of this:
setLayerType(LAYER_TYPE_HARDWARE, q);

Issue on TextView width when creating my own TextView

I created my own TextView by extending the TextView class in order to improve its display. I created various Paint and stuff to add a kind of margin. Then text has to be displayed right after the margin. If I set
android:layout_width="fill_parent"
the display is ok and my line is fully filled with a white background (as defined in my layout).
BUT if I set
android:layout_width="wrap_content"
the display goes wrong and the end of the text of my TextView is cropped. I guess this is due to the fact that I made a Translate in the onDraw method of my TextView but I don't know how to fix it.
Please note that I need the set wrap_content because I want to add another TextBox right after, and a LinearLayout around both, but for the moment the other TextBox erase a part of the content of the first one.
The code of my new TextBox is the following one :
package com.flo.ui;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.TextView;
import com.flo.musicalnotes.R;
public class NoteItemTextView extends TextView {
// Properties
private Paint marginPaint;
private Paint linePaint;
private Paint circlePaint;
private int paperColor;
private float margin;
private float marginEnd;
private float textStart;
// Initialization
public NoteItemTextView(Context context) {
super(context);
this.Init(context);
}
public NoteItemTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.Init(context);
}
private void Init(Context context)
{
// Resources retrieval
Resources myResources = getResources();
// Brush definition
this.marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.marginPaint.setColor(myResources.getColor(R.color.marginColor));
this.marginPaint.setStrokeWidth((float) 1.8);
this.linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.linePaint.setColor(myResources.getColor(R.color.underlineColor));
this.circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.circlePaint.setColor(myResources.getColor(R.color.marginColor));
this.circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
// various resources
this.paperColor = myResources.getColor(R.color.bgColor);
this.margin = myResources.getDimension(R.dimen.marginSize);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int ot = getResources().getConfiguration().orientation;
switch(ot)
{
case Configuration.ORIENTATION_LANDSCAPE:
this.marginEnd = this.margin + metrics.widthPixels / 100;
this.textStart = this.marginEnd + metrics.widthPixels / 100;
case Configuration.ORIENTATION_PORTRAIT:
this.marginEnd = this.margin + metrics.heightPixels / 100;
this.textStart = this.marginEnd + metrics.heightPixels / 100;
default:
this.marginEnd = this.margin + 5;
this.textStart = this.marginEnd + 10;
}
}
//#Override
protected void onDraw(Canvas canvas) {
// paper color
canvas.drawColor(this.paperColor);
// lines drawing
canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight(), this.linePaint);
// marge drawing
canvas.drawLine(this.margin, 0, this.margin, getMeasuredHeight(), this.marginPaint);
canvas.drawLine(this.marginEnd, 0, this.marginEnd, getMeasuredHeight(), this.marginPaint);
double x = (this.textStart + this.marginEnd) / 1.8;
float y1 = getMeasuredHeight() / 3;
float y2 = getMeasuredHeight() * 2 / 3;
float radius = (float) 2.5;
canvas.drawCircle((float) x, y1, radius, this.circlePaint);
canvas.drawCircle((float) x, y2, radius, this.circlePaint);
canvas.save();
canvas.translate(this.textStart, 0);
super.onDraw(canvas);
canvas.restore();
}
}
Thanks for your help !
Try to add this code to your custom textview class
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
int width = getMeasuredWidth();
Log.e(getClass().getSimpleName() , String.format("height x %s ::: width x %s ",height , width));
float density = getResources().getDisplayMetrics().density;
//Extra space after last letter.
float px = 2 * density;
int adjustedWidth = (int) (width + textStart + px);
setMeasuredDimension(adjustedWidth, height);
}
add this to your textview
android:paddingRight="25dp"

Circle with marker

I wish I could implement in Android what I show in this screenshot:
The number inside the circle there is no problem for me (simply make some accounts). But I do not know how to put the circle or as putting the marker.
I mean, it's like a speedometer. Then I want depending on the numerical value, the marker is in the position of the circle that matches the numerical value (the value is moved in a range of 0-100, so that the minimum value of the marker in the circle will be 0 or 100, obviously).
I'm a bit stuck with this, any help would be welcome. Thank you.
i created a circleView for you..just give a try...
CircleView.java
package com.example.err2;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class Circle extends View {
int radius, number, fontSize = 80;
Paint myPaint;
public void setRadius(int radius) {
this.radius = radius;
}
public void setNumber(int number) {
this.number = number;
}
private void init() {
Log.d("init", "start");
myPaint = new Paint();
myPaint.setColor(Color.RED);
}
public Circle(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.save();
// Drawing main crcle
canvas.drawCircle(getWidth() / 2,
getHeight() / 2,
radius, myPaint);
myPaint.setColor(Color.WHITE);
canvas.drawCircle(getWidth() / 2,
getHeight() / 2,
radius - 10, myPaint);
// end of main circle
// drawing text-number
myPaint.setColor(Color.BLACK);
myPaint.setTextSize(fontSize);
myPaint.setTextAlign(Align.CENTER);
myPaint.setFakeBoldText(true);
canvas.drawText(number + "",
getWidth() / 2,
getHeight() / 2 + fontSize / 3, myPaint);
// end of drwaing text
// drawing point on circle boundry
// findPointLocation();
double deg = number * 3.6f;
double radians = Math.toRadians(deg);
int px = (int) Math.abs(radius * Math.sin(radians));
int py = (int) Math.abs(radius * Math.cos(radians));
if (number <= 25) {
px = -px;
} else if (number <= 50) {
px = -px;
py = -py;
} else if (number <= 75) {
py = -py;
}
// end od find point
myPaint.setColor(Color.GREEN);
canvas.drawCircle(getWidth() / 2 + px, getHeight() / 2 + py, 15,
myPaint);
// end of drawing point
canvas.restore();
}
}
below given the mainactivity code
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Circle circle=(Circle)findViewById(R.id.circle1);
circle.setRadius(100);
circle.setNumber(90);
}
}
given below xml code
XML
<com.example.err2.Circle
android:id="#+id/circle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="73dp"
android:background="#778888" />

Categories

Resources