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
Related
I want to set my bitmap converted image in relative layout with the help of custom view but my image not set in the center of relative layout and its not showing complete image
My relative layout where I set my bitmap image`package org.boostram.justcolor;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.OnColorChangedListener;
import com.flask.colorpicker.OnColorSelectedListener;
import org.boostram.justcolor.Utils.util;
import static android.R.attr.src;
public class FillPaintActivity extends Activity implements View.OnTouchListener {
private RelativeLayout dashBoard;
Paint paint;
private MyView myView;
int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this);
setContentView(R.layout.activity_fill_paint);
ColorPickerView colorPickerView = (ColorPickerView) findViewById(R.id.color_picker_view);
// colorPickerView.setColor(Color.WHITE,true);
paint.setColor(Color.WHITE);
colorPickerView.setInitialColor(Color.WHITE, true);
colorPickerView.addOnColorChangedListener(new OnColorChangedListener() {
#Override
public void onColorChanged(int selectedColor) {
a = 1;
paint.setColor(selectedColor);
// Handle on color change
// Log.d("ColorPicker", "onColorChanged: 0x" + Integer.toHexString(selectedColor));
}
});
colorPickerView.addOnColorSelectedListener(new OnColorSelectedListener() {
#Override
public void onColorSelected(int selectedColor) {
paint.setColor(selectedColor);
// myView.changePaintColor(selectedColor);
Toast.makeText(FillPaintActivity.this, "selectedColor: " +
Integer.toHexString(selectedColor).toUpperCase(),
// Toast.LENGTH_SHORT).show();
}
});
dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
dashBoard.addView(myView);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
public class MyView extends View {
// private Paint paint;
private Path path;
public Bitmap mBitmap;
public ProgressDialog pd;
final Point p1 = new Point();
public Canvas canvas;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
pd = new ProgressDialog(context);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
// paint.setStrokeWidth(5f);
// BitmapDrawable drawable = (BitmapDrawable)
context.getDrawable(R.drawable.unnamed);
// Bitmap bmp = drawable.getBitmap();
// Bitmap mBitmap = Bitmap.createScaledBitmap(bmp, 120, 120,
false);
mBitmap = BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true);
//mBitmap =
Bitmap.createScaledBitmap((BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true)),1500,1380,false);
this.path = new Path();
}
#Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
// Display display = getWindowManager().getDefaultDisplay();
// int displayWidth = display.getWidth();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(getResources(), util.Id, options);
// int width = options.outWidth;
// if (width > displayWidth)
// {
// int widthRatio = Math.round((float) width / (float)
displayWidth);
// options.inSampleSize = widthRatio;
// }
// options.inJustDecodeBounds = false;
// Bitmap scaledBitmap =
BitmapFactory.decodeResource(getResources(),util.Id , options);
canvas.drawBitmap(mBitmap,0,0 ,paint);
// mBitmap = BitmapFactory.decodeResource
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (a == 0) {
Toast.makeText(FillPaintActivity.this, "Select Any Color First",
Toast.LENGTH_SHORT).show();
}
// Toast.makeText(FillPaintActivity.this, myView.getWidth()+""+myView.getHeight(), Toast.LENGTH_LONG).show();
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
p1.x = (int) x;
p1.y = (int) y;
if (p1.x < mBitmap.getWidth() && p1.y < mBitmap.getHeight()) {
final int sourceColor = mBitmap.getPixel((int) x, (int) y);
final int targetColor = paint.getColor();
new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
invalidate();
}
// else {
// Toast.makeText(FillPaintActivity.this, "You touched outside the Image", Toast.LENGTH_SHORT).show();
// }
}
return true;
}
public void clear() {
path.reset();
invalidate();
}
public void changePaintColor(int color) {
paint.setColor(color);
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
this.bmp = bm;
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
}
#Override
protected void onPreExecute() {
// pd.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill floodFill = new FloodFill(bmp, targetColor, replacementColor);
floodFill.floodFill(pt.x, pt.y);
return null;
}
#Override
protected void onPostExecute(Void result) {
invalidate();
}
}
}
}
https://i.stack.imgur.com/AHpcb.png
My bitmap converted image not set in center of relative layout through view. Kindly help me i'm stuck here for almost two week. Help
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
enter image description here
package test;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.ImageSource;
import java.util.ArrayList;
import java.util.List;
import common.PinView;
public class RoomFragment extends Fragment{
PinView imageView;
LinearLayout layoutFooter;
List<PointF> pinList = new ArrayList<PointF>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.room_fragment_layout, container, false);
//footer action bar
layoutFooter = (LinearLayout) rootView.findViewById(R.id.footer_room);
layoutFooter.setVisibility(LinearLayout.INVISIBLE);
//End footer action bar
//image plane and pin
imageView = (PinView) rootView.findViewById(R.id.plane);
imageView.setImage(ImageSource.resource(R.drawable.plane));
imageView.setZoomEnabled(false);
pinList.add(new PointF(100f, 1200f));
pinList.add(new PointF(400f, 1200f));
pinList.add(new PointF(1000f, 1200f));
imageView.setPins(pinList);
//imageView.setPin(new PointF(800f, 1200f));
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
layoutFooter.setVisibility(LinearLayout.INVISIBLE);
if(motionEvent.getAction() == MotionEvent.ACTION_UP){
Toast.makeText(getContext(), motionEvent.getX() + " | " + motionEvent.getY(), Toast.LENGTH_SHORT).show();
layoutFooter.setVisibility(LinearLayout.VISIBLE);
}
imageView.setPin(new PointF(motionEvent.getX(), motionEvent.getY()));
return false;
}
});
//End image plane and pin
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
package common;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.util.List;
import product.dm.com.dm.R;
public class PinView extends SubsamplingScaleImageView {
private PointF sPin;
private Bitmap pin;
private List<PointF> pinList;
public PinView(Context context) {
this(context, null);
}
public PinView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
}
public void setPin(PointF sPin) {
this.sPin = sPin;
initialise();
invalidate();
}
public void setPins(List<PointF> pinList){
this.pinList = pinList;
initialise();
}
public PointF getPin() {
return sPin;
}
private void initialise() {
float density = getResources().getDisplayMetrics().densityDpi;
pin = BitmapFactory.decodeResource(this.getResources(), R.drawable.pin_red);
float w = (density/420f) * pin.getWidth();
float h = (density/420f) * pin.getHeight();
pin = Bitmap.createScaledBitmap(pin, (int)w, (int)h, true);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isReady()) {
return;
}
Paint paint = new Paint();
paint.setAntiAlias(true);
if (sPin != null && pin != null) {
PointF vPin = sourceToViewCoord(sPin);
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paint);
}
for(int i=0;i<pinList.size();i++){
Paint paints = new Paint();
paint.setAntiAlias(true);
PointF vPin = sourceToViewCoord(pinList.get(i));
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paints);
}
}
}
Hello :) I created a yellow canvas with a ball on it, now i'm trying to move the ball but I don't know how, it's the first time i'm using an accelerometer and it's my first time using canvas and draw.. So can you help me moving it?
Here is my code so far:
package com.example.theball;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.view.Display;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private int c = Color.YELLOW;
private Canvas g;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
draw();
}
#SuppressWarnings("deprecation")
public void draw ()
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getHeight();
int height = display.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
g = new Canvas(bitmap);
g.drawColor(c);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
g.drawCircle(50, 10, 25, paint);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
setContentView(layout);
}
public void onSensorChanged(SensorEvent event)
{
}
}
SOLVED: here is the new code, thanks to someone here from stackoverflow:
package com.example.theball;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
#SuppressWarnings("deprecation") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
}
}
public class AnimatedView extends ImageView {
static final int width = 50;
static final int height = 50;
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
mDrawable.draw(canvas);
invalidate();
}
}
}
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);
}
}