I want to draw rectangle on screen. But I don't run programme. Because, I am writing wrong code. Therefore, I am not writing MainActivity below. Can you help me to use the onDraw method?
Best Regards.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Deneme.java
public class Deneme extends View {
Paint myPaint;
public Deneme(Context context) {
super(context);
myPaint = new Paint();
myPaint.setColor(Color.BLACK);
myPaint.setStyle(Paint.Style.FILL);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0,0,canvas.getWidth(),canvas.getHeight()/2);
canvas.drawRect(ourRect,myPaint);
}
}
You can try this:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
public class Deneme extends View {
private Rect mRectangle;
private Paint mPaint;
public Deneme(Context context) {
super(context);
int x = 50;
int y = 50;
int sideLength = 200;
// create a rectangle that we'll draw later
mRectangle = new Rect(x, y, sideLength, sideLength);
// create the Paint and set its color
mPaint = new Paint();
mPaint.setColor(Color.GRAY);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawRect(mRectangle, mPaint);
}
}
Fast way
And your activity:
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new Deneme(this));
}
}
Also you can try this elegant way:
In your layout activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.package.RectangleActivity">
</RelativeLayout>
In your activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.package.Deneme;
import com.package.R;
public class MainActivity extends AppCompatActivity {
private RelativeLayout mRelativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add RelativeLayout
mRelativeLayout =(RelativeLayout) findViewById(R.id.activity_main_relative_layout);
//add LayoutParams
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
Deneme rectangle = new Deneme(this);
rectangle.setLayoutParams(params);
mRelativeLayout.addView(rectangle);
}
}
You'll find the supporting medium article!!!
and this example in GitHub
if you want to draw a rectangle use this code
public class Deneme extends View {
Paint myPaint;
public Deneme(Context context) {
super(context);
init();
}
public Deneme(Context context, AttributeSet attributeSet)
{
super(context,attributeSet);
init();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0,0,canvas.getWidth(),canvas.getHeight()/2);
canvas.drawRect(ourRect,myPaint);
}
public void init()
{
myPaint = new Paint();
myPaint.setColor(Color.BLACK);
myPaint.setStyle(Paint.Style.FILL);
}
}
use this class while designing your xml file and rectangle would appear
Related
In my face detector project, I'm using a custom ImageView (MyView) to detect faces and draw rectangles on the detected faces. For this I have set fixed dimensions for my customview (MyView) and trying to scale the bitmap to fit the customview. But somehow I'm not able to achieve this.
I have gone throught all similar questions on SO. Please help.
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.sample.facedetector.MyView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/MyViewId"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:scaleType="centerCrop"/>
MainActivity
package com.sample.facedetector;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView faceDetectorView = (MyView) findViewById(R.id.MyViewId);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.face_detector).copy(Bitmap.Config.RGB_565,true);
faceDetectorView.setImage(bmp);
faceDetectorView.setScaleType(ImageView.ScaleType.CENTER_CROP);
faceDetectorView.detectFaces();
}
MyView
package com.sample.facedetector;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageView;
public class MyView extends ImageView {
private Bitmap mFaceBitmap;
private int count = 0;
private FaceDetector.Face[] faces;
private Bitmap image;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void detectFaces(){
FaceDetector myFaceDetector = null;
mFaceBitmap = image.copy(Bitmap.Config.RGB_565, true);
int targetWidth = mFaceBitmap.getWidth();
int targetHeight = mFaceBitmap.getHeight();
faces= new FaceDetector.Face[5];
int[] fpx =null;
int[] fpy = null;
myFaceDetector = new FaceDetector(targetWidth,targetHeight,5);
count = myFaceDetector.findFaces(mFaceBitmap, faces);
setWillNotCacheDrawing(true);
requestLayout();
this.invalidate();
}
/*#Override
public void setScaleType(ScaleType scaleType) {
super.setScaleType(ScaleType.CENTER);
invalidate();
}*/
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mFaceBitmap,0,0,null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
if (count > 0) {
for (int i = 0; i < count; i++) {
FaceDetector.Face face = faces[i];
PointF midPoint = new PointF();
face.getMidPoint(midPoint);
float eyeDistance = face.eyesDistance();
canvas.drawRect(midPoint.x-eyeDistance, midPoint.y-eyeDistance, midPoint.x+eyeDistance, midPoint.y+eyeDistance, myPaint);
}
}
}
#Override
public void setImageResource(#DrawableRes int resId) {
super.setImageResource(resId);
invalidate();
}
public void setImage(Bitmap image) {
this.image = image;
}
}
When I try to run this code I get an error in the view activity stating that void is an invalid type for the function "protected void onDraw(Canvas canvas)".
This is the main activity
package com.example.crazyeights;
import android.app.Activity;
import android.os.Bundle;
public class CrazyEightsActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
CrazyEightsView myView = new CrazyEightsView(this);
setContentView(myView);
}
}
This is the View activity
package com.example.crazyeights;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class CrazyEightsView extends View
{
private Paint redPaint;
private int circleX;
private int circleY;
private float radius;
public CrazyEightsView(Context context)
{
super(context);
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setColor(Color.RED);
circleX = 100;
circleY = 100;
radius = 30;
This is where the error occurs.
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawCircle(circleX, circleY, radius, redPaint);
}
}
}
Move onDraw out of the constructor.
public CrazyEightsView(Context context)
{
super(context);
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setColor(Color.RED);
circleX = 100;
circleY = 100;
radius = 30;
} // <-- put } here
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawCircle(circleX, circleY, radius, redPaint);
}
//} <-- used to be here
I have the following problem.
I am trying to code a Tetris Game for Android. Therefore I need to put a Grid on the GameView (a self coded class, which extends the SurfaceVieW).
Unfortunately I do not know how to draw the Grid on the GameView.
I already implemented a Grid class, which sets the width and height of the rows and columns.
My Grid Class
package com.example.tetris;
import android.content.Context;
import android.graphics.Paint;
import android.widget.GridView;
public class Grid extends GridView
{
private int rowsWidth;
private int columnsHeight;
private int rowsNum;
private int columnsNum;
private Paint gridcolor;
private GameView gameview;
public Grid(Context context)
{
super(context);
}
public void drawGrid(GameView gameview)
{
this.gameview = gameview;
rowsWidth = gameview.getWidth() / 10;
rowsNum = gameview.getWidth() / rowsWidth;
columnsHeight = gameview.getHeight()/rowsWidth;
columnsNum = gameview.getHeight() / columnsHeight;
setHorizontalSpacing(1);
setColumnWidth(rowsWidth);
setNumColumns(columnsNum);
}
}
My GameView Class
package com.example.tetris;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.GridView;
public class GameView extends SurfaceView {
private SurfaceHolder surfaceHolder;
private Tetriminos[] tetriminos[];
private GridView grid;
public GameView(Context context)
{
super(context);
final GameLoopThread gameloop = new GameLoopThread(this); // warum er final erzwingt, ka
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback()
{
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
gameloop.setRunning(true);
gameloop.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
gameloop.setRunning(false);
}
});
}
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
drawBorders(canvas);
// grid.drawGrid(this);
}
public boolean onTouchEvent(MotionEvent event) {
return false;
}
public void drawBorders(Canvas canvas)
{
int borderwidth = 10;
int screenWidth = getWidth();
int screenHeight = getHeight();
Paint bordercolor = new Paint();
bordercolor.setARGB(255, 236, 27, 36);
canvas.drawRect(0, 0, borderwidth, getHeight(), bordercolor);
canvas.drawRect(0, getHeight()-borderwidth, getWidth(), getHeight(), bordercolor);
canvas.drawRect(getWidth()-borderwidth, 0, getWidth(), getHeight(), bordercolor);
canvas.drawRect(0, 0, getWidth(), borderwidth, bordercolor);
}
}
I want to rotate circle continuously in canvas on android. i am drawing circle using canvas and i am rotate circle continuously.it is possible,if possible how do it
with code or example can help me with greatly appreciated!
Here's my code for draw circle on canvas:
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 AnimationActivity extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
public class SampleView extends View
{
public SampleView(Context context)
{
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas)
{
Paint mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.RED);
canvas.drawCircle(75, 75, 75, mPaint);
}
}
}
Thanks in Advance!
You can use Animation to rotate the circle you've drawn (using Canvas). The code below works. I've modified your code and added necessary changes.
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 AnimationActivity extends Activity {
public class SampleView extends View {
Paint mPaint = new Paint();
private Animation anim;
public SampleView(Context context) {
super(context);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.RED);
}
private void createAnimation(Canvas canvas) {
anim = new RotateAnimation(0, 360, getWidth()/2, getHeight()/2);
anim.setRepeatMode(Animation.RESTART);
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(10000L);
startAnimation(anim);
}
protected void onDraw(Canvas canvas) {
int cx = getWidth()/2; // x-coordinate of center of the screen
int cy = getHeight()/2; // y-coordinate of the center of the screen
// Starts the animation to rotate the circle.
if (anim == null)
createAnimation(canvas)
canvas.drawCircle(cx, cy, 150, mPaint); // drawing the circle.
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
}
Enjoy!
canvas.rotate(-rotate_angle, rotate_center_x, rotate_center_y);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
RectF oval3 = new RectF(rotate_center_x-150, rotate_center_y-50, rotate_center_x+150, rotate_center_y+50);
canvas.drawOval(oval3, paint);
//resume original angle
canvas.rotate(rotate_angle, rotate_center_x, rotate_center_y);
For More Information, click here.. :)
I have a child view and I want the canvas that to draw a circle that has "pixels" in the negative side of the axis
canvas.drawCircle(0, 0, 50f, paint);
In order to do that i use clipRect, this works fine and i see the full cirlce.
However when I use requestLayout on the parent view and changes the x,y postion of the child view
the negative sids of the circle are not shown
please advise me what to do
here is the code:
package natan.android.TestCanvas;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class TestCanvasActivity extends Activity {
View childView;
RelativeLayout parentView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
childView = new View(this)
{
#Override
protected void onDraw(Canvas canvas) {
canvas.clipRect(-50, -50, 50, 50,android.graphics.Region.Op.REPLACE);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawCircle(0, 0, 50f, paint);
super.onDraw(canvas);
}
};
parentView = new RelativeLayout(this);
parentView.addView(childView);
LayoutParams layoutParms = (LayoutParams)(childView.getLayoutParams());
layoutParms.leftMargin=150;
layoutParms.topMargin=150;
setContentView(parentView);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
LayoutParams layoutParms = (LayoutParams)(childView.getLayoutParams());
layoutParms.leftMargin=100;
layoutParms.topMargin=100;
parentView.requestLayout();
return super.onTouchEvent(event);
}
}
I think i figured out a soulation
I took it from here
http://www.devdaily.com/java/jwarehouse/android/core/java/android/view/ViewGroup.java.shtml
using this line of codes fixed the problem
parentView.setClipChildren(false);
and
parentView.requestLayout();
parentView.invalidate();
Hopes this helps someone else and If someone has more insight on this problem please add it
here is the full code:
public class TestCanvasActivity extends Activity {
View childView;
RelativeLayout parentView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
childView = new View(this)
{
#Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawCircle(0, 0, 50f, paint);
super.onDraw(canvas);
}
};
parentView = new RelativeLayout(this)
{
#Override
protected void onLayout(boolean changed, int l, int t,
int r, int b) {
// TODO Auto-generated method stub
super.onLayout(changed, l, t, r, b);
}
};
parentView.setClipChildren(false);
parentView.addView(childView);
parentView.setClipChildren(false);
LayoutParams layoutParms = (LayoutParams)(childView.getLayoutParams());
layoutParms.leftMargin=150;
layoutParms.topMargin=150;
setContentView(parentView);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
LayoutParams layoutParms = (LayoutParams)(childView.getLayoutParams());
layoutParms.leftMargin=100;
layoutParms.topMargin=100;
parentView.requestLayout();
parentView.invalidate();
return super.onTouchEvent(event);
}
}