I build this class to draw on screen to implement some brushes created via differents Paints and paths.
Currently is drawing a square based on user touch movement, but the draw path is being rotated by the draw direction of the touch. I tried to apply a rect without no luck and I don't found any related info about this phenom
EDIT :
This image is from current result
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class RachetBasic extends androidx.appcompat.widget.AppCompatImageView {
private Canvas canvas;
private Bitmap bitmap;
private Paint bitmapPaint = new Paint(Paint.DITHER_FLAG);
private Path squarePath = new Path();
private Paint squarePaint = new Paint();
public RachetBasic(Context context) {
super(context);
}
public RachetBasic(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RachetBasic(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onSizeChanged(int width, int height, int oldw, int oldh) {
super.onSizeChanged(width, height, oldw, oldh);
squarePaint.setAntiAlias(true);
squarePaint.setDither(true);
squarePaint.setStyle(Paint.Style.STROKE);
squarePaint.setStrokeCap(Paint.Cap.SQUARE);
squarePaint.setStrokeWidth(80);
squarePaint.setColor(Color.BLUE);
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, bitmapPaint);
canvas.drawPath(squarePath, squarePaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
squarePath.moveTo(x, y);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
squarePath.lineTo(x, y);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
squarePath.lineTo(x, y);
canvas.drawPath(squarePath, squarePaint);
squarePath.reset();
}
invalidate();
return true;
}
}
public class MainActivity extends androidx.appcompat.app.AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new RachetBasic(MainActivity.this));
}
}
Related
I asked this question before, but now I've stumbled around and figured out a direction.
Basically, I need to record the user's finger's movements around the screen, and replay an animation of that movement on a view upon pressing a replay button, as well as a reverse animation of it when pressing a reverse button. I'm trying to achieve this by saving the finger's (x,y) coordinates in onTouch(), which I store in an ArrayList for PointF objects, then create a path for the view to animate on based on the coordinates stored in said ArrayList. Then I'll need to animate along that path. However, I am not sure how to create a path based on an arraylist that could be of any length.
Code related to the animation so far:
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import java.util.ArrayList;
/**
* TODO: document your custom view class.
*/
public class MyView extends View {
ArrayList<PointF>theCoords;
ArrayList<Float> xcord;
ArrayList<Float> ycord;
private Paint paint;
//coordinates
private float x;
private float y;
public MyView (Context context, AttributeSet attrs) {
super(context, attrs);
initPaint();
xcord = new ArrayList<Float>();
ycord= new ArrayList<Float>();
theCoords=new ArrayList<PointF>();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPaint();
xcord = new ArrayList<Float>();
ycord= new ArrayList<Float>();
theCoords=new ArrayList<PointF>();
}
public MyView(Context context) {
super(context);
initPaint();
xcord = new ArrayList<Float>();
ycord= new ArrayList<Float>();
theCoords=new ArrayList<PointF>();
}
//initialize paint object
private void initPaint(){
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setTextSize(40);
}
#Override
//drawing on the canvas
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x,y,50,paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
theCoords.clear();
xcord.clear();
ycord.clear();
x = event.getX();
y = event.getY();
PointF p1 = new PointF(x,y);
theCoords.add(p1);
postInvalidate();
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
x = event.getX();
y = event.getY();
PointF p2 = new PointF(x,y);
theCoords.add(p2);
postInvalidate();
break;
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.R)
public void replayAnim()
{
PointF pcur;
PointF pnext;
//create path
for(int i =0;i<theCoords.size()-1;i++)
{
pcur=new PointF(theCoords.get(i));
pnext=new PointF(theCoords.get(i+1));
//how to form a path with these?
}
//anim along the path
}
public void reverseAnim()
{
//the original code I have, which only
//moves the view to its original position
for (int i = xcord.size() - 1; i >= 0; i--)
{
x = xcord.get(i);
y = ycord.get(i);
Log.d("ReverseAnimation", "x: " + Float.toString(x));
postInvalidate();
}
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
} ```
I want to resize my widgets in the layout by ratio, but I can't.
At time I resizing ViewPager or com.daimajia.slider.SliderLayout by ratio and Measure, but childs of ViewPager or com.daimajia.slider.SliderLayout lose their height.
I create a custom widget for this work.
Code example for ImageView:
package ...;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
public class SquareImageView extends android.support.v7.widget.AppCompatImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
setMeasuredDimension(width, width);
}
#Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
int w = 0, h = 0;
if (getWidth() == 0 || getHeight() == 0) {
if (getMeasuredWidth() == 0 || getMeasuredHeight() == 0) {
return;
}
else {
w = getMeasuredWidth();
h = getMeasuredHeight();
}
return;
}
else {
w = getWidth();
h = getHeight();
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
final Rect rect = new Rect(0, 0, w, w);
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, rect, rect, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
My Codes not worked for this widgets:
ViewPager, com.daimajia.slider.SliderLayout.
//--------------------------------------------------------
//--------------------------------------------------------
//------------> ***** Answer - Go Down ***** <------------
//--------------------------------------------------------
//------------> ***** Answer - Go Down ***** <------------
//--------------------------------------------------------
//------------> ***** Answer - Go Down ***** <------------
//--------------------------------------------------------
//--------------------------------------------------------
I found the answer my question.
public class ViewPagerByRatioSize extends ViewPager {
Integer layout_ratioX = 0, layout_ratioY = 0;
public ViewPagerByRatioSize(Context context) {
super(context);
}
public ViewPagerByRatioSize(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerByRatioSize, 0, 0);
try {
layout_ratioX = typedArray.getInteger(R.styleable.ViewPagerByRatioSize_layout_ratioXViewPager, 0);
layout_ratioY = typedArray.getInteger(R.styleable.ViewPagerByRatioSize_layout_ratioYViewPager, 0);
}
finally {
typedArray.recycle();
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = getMeasuredWidth();
super.setMeasuredDimension(width, width / layout_ratioX * layout_ratioY);
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(width / layout_ratioX * layout_ratioY, MeasureSpec.AT_MOST));
}
}
This code worked for me, but I change codes because my application can't get values from xml codes.
This new codes:
public class ViewPagerByRatioSize extends ViewPager {
public ViewPagerByRatioSize(Context context) {
super(context);
}
public ViewPagerByRatioSize(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = getMeasuredWidth();
super.setMeasuredDimension(width, width / 3 * 2);
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(width / 3 * 2, MeasureSpec.AT_MOST));
}
}
Successful for ever :)
I am starting with my first attempts to write an android app. I'd like to to visualize the Monte-Carlo-Approximation for pi. Hence I first want to draw a Circle onto a view but i dont get it working!
I have tried to create my own "CircleView" Class which extends "View" and overwrite the onDraw(..) method like its explained over here: How to draw circle by canvas in Android?
This is my CircleView Class
public class CircleView extends View {
public CircleView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(150);
canvas.drawCircle(50,50,20,paint);
}
}
I have inserted the CircleView into a LinearLayout with the following XML-code
<com.tak3r07.montecarlopi.CircleView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/circleView"
android:layout_weight="1"/>
(Btw Android Studio is telling me in the XML-view at the right side: "Rendering Problems Custom view CircleView is not using the 2- or 3-argument View constructors; XML attributes will not work")
The App just crashes with the following log: http://pastebin.com/Gv1GaHtX
Can someone tell what i did wrong?
I thought this setup would create an activity with a view which displays a circle.
Regards
Edit: Crash is fixed by adding the 2 and 3 Parameter Constructor in CircleView (See https://stackoverflow.com/a/13797457/3248708)
But now i still do not see any Circle in the activity
A couple of observations:
You need to take into account the width and height assigned to your view when determining your circle's center point and radius.
You should take into account the padding assigned to your View so you don't draw in that reserved portion.
You should avoid allocating objects within your onDraw method since this gets called a lot.
In order to allow your view to be specified in an XML layout, you need to provide the constructor that takes a Context and an AttributeSet. The AttributeSet is the mechanism by which your XML attributes are passed to your view.
Give this a try:
package com.tak3r07.montecarlopi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class CircleView extends View
{
private static final int DEFAULT_CIRCLE_COLOR = Color.RED;
private int circleColor = DEFAULT_CIRCLE_COLOR;
private Paint paint;
public CircleView(Context context)
{
super(context);
init(context, null);
}
public CircleView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs)
{
paint = new Paint();
paint.setAntiAlias(true);
}
public void setCircleColor(int circleColor)
{
this.circleColor = circleColor;
invalidate();
}
public int getCircleColor()
{
return circleColor;
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
int pl = getPaddingLeft();
int pr = getPaddingRight();
int pt = getPaddingTop();
int pb = getPaddingBottom();
int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);
int radius = Math.min(usableWidth, usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);
paint.setColor(circleColor);
canvas.drawCircle(cx, cy, radius, paint);
}
}
You can create a Circular layout and inside this view, every childs should be rounded up :
public class CircleView extends FrameLayout {
private Bitmap maskBitmap;
private Paint paint, maskPaint;
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas) {
Bitmap offscreenBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas offscreenCanvas = new Canvas(offscreenBitmap);
super.draw(offscreenCanvas);
if (maskBitmap == null) {
maskBitmap = createMask(getWidth(), getHeight());
}
offscreenCanvas.drawBitmap(maskBitmap, 0f, 0f, maskPaint);
canvas.drawBitmap(offscreenBitmap, 0f, 0f, paint);
}
private Bitmap createMask(int width, int height) {
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(mask);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, width, height, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(new RectF(0, 0, width, height), width/2f, height/2f, paint);
return mask;
}
}
I'm currently experimenting with my first custom View in android and have been trying to draw points on a canvas via a onTouchEvent but have failed after several attempts. The View does detect my touches and successfully prints out a System.out.println message when touched however it still doesn't draw on the canvas.
After several various attempts this is what I came up with:
package com.techdigy.testapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawingBoard extends View {
Canvas canvas;
Bitmap bmp;
BitmapDrawable temp;
public DrawingBoard(Context context, AttributeSet attributeSet) {
super(context,attributeSet);
// TODO Auto-generated constructor stub
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas();
}
protected void onDraw(Canvas canvas) {
//draw view
}
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float touchX = event.getX();
float touchY = event.getY();
Paint paint = new Paint();
System.out.println("test");
this.canvas.drawPoint(touchX, touchY, paint);
temp = new BitmapDrawable(this.bmp);
this.setBackground(this.temp);
invalidate();
return true;
}
}
try this...
public class DrawingBoard extends View {
private Bitmap bmp;
private float touchX;
private float touchY;
private Paint paint;
public DrawingBoard(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
setBackgroundDrawable(new BitmapDrawable(getResources(), bmp));
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPoint(touchX, touchY, paint);
}
public boolean onTouchEvent(MotionEvent event) {
// detect user touch
touchX = event.getX();
touchY = event.getY();
System.out.println("test");
invalidate();
return true;
}
}
I want to draw circle by canvas. Here is my code:
[MyActivity.java]:
public class MyActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
...
setContentView(new View(this,w,h));
}
}
[View.java]:
public class View extends SurfaceView
{
public View(Context context, int w, int h)
{
super(context);
Canvas grid = new Canvas(Bitmap.createBitmap(h,w, Bitmap.Config.ARGB_8888));
grid. drawColor(Color.WHITE);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
grid.drawCircle(w/2, h/2 , w/2, paint);
}
}
So I have just black screen without circle.
Why it does not work? How to fix it?
You can override the onDraw method of your view and draw the circle.
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, radius, paint);
}
For a better reference on drawing custom views check out the official Android documentation.
http://developer.android.com/training/custom-views/custom-drawing.html
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
Edit
if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using
canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);
These two link also help
http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o
http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html
public class CircleView extends View {
private static final String COLOR_HEX = "#E74300";
private final Paint drawPaint;
private float size;
public CircleView(final Context context, final AttributeSet attrs) {
super(context, attrs);
drawPaint = new Paint();
drawPaint.setColor(Color.parseColor(COLOR_HEX));
drawPaint.setAntiAlias(true);
setOnMeasureCallback();
}
#Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(size, size, size, drawPaint);
}
private void setOnMeasureCallback() {
ViewTreeObserver vto = getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
removeOnGlobalLayoutListener(this);
size = getMeasuredWidth() / 2;
}
});
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void removeOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT < 16) {
getViewTreeObserver().removeGlobalOnLayoutListener(listener);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
}
Xml example: will produce a circle of 5dp
<com.example.CircleView
android:layout_width="10dp"
android:layout_height="10dp"/>
If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
setupPaint();
}
}
Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)
private Paint drawPaint;
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(Color.BLUE);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
And initialise canvas object
private Canvas canvas;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}
And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw
canvas.invalidate();
For more details on canvas drawing refer https://medium.com/#mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b
#Override
public void onDraw(Canvas canvas){
canvas.drawCircle(xPos, yPos,radius, paint);
}
Above is the code to render a circle. Tweak the parameters to your suiting.
Try this
The entire code for drawing a circle or download project source code and test it on your android studio. Draw circle on canvas programmatically.
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.widget.ImageView;
public class Shape {
private Bitmap bmp;
private ImageView img;
public Shape(Bitmap bmp, ImageView img) {
this.bmp=bmp;
this.img=img;
onDraw();
}
private void onDraw(){
Canvas canvas=new Canvas();
if (bmp.getWidth() == 0 || bmp.getHeight() == 0) {
return;
}
int w = bmp.getWidth(), h = bmp.getHeight();
Bitmap roundBitmap = getRoundedCroppedBitmap(bmp, w);
img.setImageBitmap(roundBitmap);
}
public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f, finalBitmap.getWidth() / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
Here is example to draw stroke circle canvas
val paint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = 10f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Example to draw solid circle canvas
val paint = Paint().apply {
color = Color.RED
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Hope it help
private Paint green = new Paint();
private int greenx , greeny;
green.setColor(Color.GREEN);
green.setAntiAlias(false);
canvas.drawCircle(greenx,greeny,20,green);