I have an bitmap that I want to apply an alpha mask to. I know I can easily use Porter Duff mode to do that with another bitmap, but I want to programmatically create the alpha mask because it needs to change continually. So, I'm trying to use a path to create it, but I can't make the connection between the finished path and creating the bitmap to use from that path.
Here is my layout:
<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="${relativePackage}.${activityClass}" >
<SeekBar
android:id="#+id/seekBar_percent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:progress="50" />
<ImageView
android:id="#+id/imageView_canvas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/seekBar_percent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is my main activity:
package com.wheeler.daniel.xxx;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
PathRectangle alphaPath;
ImageView canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
canvas = (ImageView) findViewById(R.id.imageView_canvas);
canvas.post(new Runnable()
{
#Override
public void run() {
Display display = getWindowManager().getDefaultDisplay();
int canvasWidth = display.getWidth();
int canvasHeight = display.getHeight();
alphaPath = new PathRectangle(getApplicationContext(), canvas, canvasWidth, canvasHeight);
}
});
SeekBar percentBar = (SeekBar) findViewById(R.id.seekBar_percent);
percentBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
alphaPath.updatePercent(progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
I created a class to draw my path (a basic rectangle to cover the image) called PathRectangle:
public class PathRectangle extends View {
ImageView layoutCanvas;
Bitmap canvasBitmap;
Paint paint;
Path path;
float width;
float height;
int percent;
Canvas tempCanvas;
public PathRectangle(Context context, ImageView canvasImage, float width, float height)
{
super(context);
layoutCanvas = canvasImage;
path = new Path();
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.FILL);
this.width = width;
this.height = height;
percent = 50;
Bitmap.Config config = Bitmap.Config.ARGB_8888;
canvasBitmap = Bitmap.createBitmap((int)width, (int)height, config);
tempCanvas = new Canvas( canvasBitmap );
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
path.reset();
path.moveTo(0,0);
path.lineTo(percent, 0);
path.lineTo(percent, height);
path.lineTo(0, height);
tempCanvas.drawPath(path, paint);
layoutCanvas.setImageBitmap(canvasBitmap);
}
public void updatePercent(int newPercent)
{
percent = (int) (width * (newPercent * .01));
invalidate();
}
}
This is just my testing to generate the Bitmap, but nothing is displayed in my ImageView. I feel like by drawing the path to the tempCanvas isn't actually drawing it to the bitmap I used in the creation of the tempCanvas.
Example of what I want:
Source Bitmap
Alpha Mask to create
Result
Related
I am setting a layer list to an imageview with drawable programatically in android
My custom Drawable is as follows,
package cl.tk.ui.iBAPView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import cl.tk.R;
public class CircleDrawable extends Drawable {
private int color;
private boolean checked = false;
private int size;
private Paint paint= new Paint(Paint.DITHER_FLAG);
private Context context;
public CircleDrawable(Context context,boolean checked,int color,int size) {
this.checked=checked;
this.color=color;
this.size=size;
this.context=context;
}
#Override
public void draw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(size/ 2, size / 2,size / 2, paint);
if (checked)
drawChecked(canvas);
}
private void drawChecked(Canvas canvas) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_check);
float posX = (canvas.getWidth() - bitmap.getWidth()) / 2;
float posY = (canvas.getHeight() - bitmap.getHeight()) / 2;
canvas.drawBitmap(bitmap, posX, posY, paint);
}
#Override
public void setAlpha(int alpha) {
// do nothing
}
#Override
public void setColorFilter(ColorFilter cf) {
// do nothing
}
#Override
public int getOpacity() {
return PixelFormat.UNKNOWN;
}
}
This is my code to create layer list drawable and set it to imageview,
public static void setChecked_Selector(Context context,ImageView view) {
try {
int size= (int) context.getResources().getDimension(R.dimen._17sdp);
/* Drawable pressed=squareView(ContextCompat.getColor(context,R.color.colorBlue),ContextCompat.getColor(context,R.color.colorRed),size);//new BadgeDrawable(context,colorPressed);
Drawable normal=squareView(ContextCompat.getColor(context,R.color.colorwhite),ContextCompat.getColor(context,R.color.colorRed),size);*/
Drawable pressed=new CircleDrawable(context,true,ContextCompat.getColor(context,R.color.colorGreen),size);
Drawable normal=new CircleDrawable(context,false,ContextCompat.getColor(context,R.color.colorGray),size);
Drawable[] drawarray = {pressed, normal};
LayerDrawable layerdrawable = new LayerDrawable(drawarray);
view.setBackgroundDrawable(layerdrawable);
view.setImageLevel(0);
view.setTag(0);
} catch (Exception e) {
}
}
and on click of imageview, i am trying to change the drawable but failed as the condition is working perfectly but layerlist drawable is not changing,
My code on click listener of imageView,
case R.id.ah_img_agree:
{
int imageLevel=-1;
if(0==(int)v.getTag())
imageLevel=1;
else
imageLevel=0;
((ImageView)v).setImageLevel(imageLevel);
rbAgreed.setTag(imageLevel);
}
break;
I'm trying to build a custom view but for some reason it's not displaying at all.
To save you reading both constructors, I am calling the View constructor without the attr parameter because these should be fetched from the Layout file. Any values that are not fetched from here are set in the view class itself.
My view class:
package mrl233.campustour.AugmentedReality;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import mrl233.campustour.R;
/**
* TODO: document your custom view class.
*/
public class CameraOverlay extends View {
private float mAzimuth;
private float mPitch;
private float mRoll;
private String mTextString;
private int mTextColor = Color.RED;
private float mTextDimension = 80;
private Drawable mTextDrawable;
private float mTextSize = 29;
private TextPaint mTextPaint;
private float mTextHeight = 0;
private float mTextWidth;
public CameraOverlay(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CameraOverlay,
0, 0);
try {
mTextString = a.getString(R.styleable.CameraOverlay_exampleString);
mAzimuth = a.getFloat(R.styleable.CameraOverlay_exampleFloat_X, 0);
mPitch = a.getFloat(R.styleable.CameraOverlay_exampleFloat_Y, 0);
mRoll = a.getFloat(R.styleable.CameraOverlay_exampleFloat_Z, 0);
} finally {
a.recycle();
}
init();
}
public CameraOverlay(Context con, float azimuth, float pitch, float roll) {
this(con,null);
this.mAzimuth = azimuth;
this.mPitch = pitch;
this.mRoll = roll;
TypedArray a = con.getTheme().obtainStyledAttributes(
null,
R.styleable.CameraOverlay,
0, 0);
try {
mTextString = a.getString(R.styleable.CameraOverlay_exampleString);
mAzimuth = a.getFloat(R.styleable.CameraOverlay_exampleFloat_X, 0);
mPitch = a.getFloat(R.styleable.CameraOverlay_exampleFloat_Y, 0);
mRoll = a.getFloat(R.styleable.CameraOverlay_exampleFloat_Z, 0);
} finally {
a.recycle();
}
init();
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
invalidate();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int contentWidth = getWidth() - paddingLeft - paddingRight;
int contentHeight = getHeight() - paddingTop - paddingBottom;
canvas.drawText("wsfsefseefsfsef",
paddingLeft + (contentWidth - mTextWidth),
paddingTop + (contentHeight + mTextHeight)
,mTextPaint);
}
}
This is my view layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:id="#+id/overlay" >
<mrl233.campustour.AugmentedReality.CameraOverlay
android:background="#ccc"
android:layout_width="300dp" android:layout_height="300dp" android:paddingLeft="20dp"
android:paddingBottom="40dp" custom:exampleDimension="24sp" custom:exampleColor="#33b5e5"
custom:exampleString="Hello, CameraOverlay"
custom:exampleFloat_X="0.1"
custom:exampleFloat_Y="0.5"
custom:exampleFloat_Z="1"/>
</FrameLayout>
I am adding this view to to an activity which has it's own view. This is the Activity class's onCreate method which is where I try to add the view.
#Override
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_augment);
preview = (FrameLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(this, camera);
mCameraOverlay = new CameraOverlay(this, 0, 0, 0);
preview.addView(mPreview);
preview.addView(mCameraOverlay);
preview.bringChildToFront(mCameraOverlay);
}
The layout of this activity class:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" tools:showIn="#layout/augment"
tools:context="mrl233.campustour.Activities.Augment">
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<!--<SurfaceView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:id="#+id/surfaceView"/>-->
<mrl233.campustour.AugmentedReality.CameraOverlay
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</RelativeLayout>
I see two problems here. You shouldn't be calling invalidate() in onDraw method cause it causes view to redraw itself(infinite loop). Secondly getWidth() might be 0 there. You might want to get canvas width from onSizeChanged method
private int width;
private int height;
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
...
int contentWidth = width - paddingLeft - paddingRight;
...
}
try playing with hardcoded sizes cause currently you might be drawing that text offscreen or giving it too little space(it might help you find the problem).
Smallest customView I can Think of would be:
public class CustomView extends View {
private TextPaint paint;
public CustomView(Context context) {
super(context);
paint = new TextPaint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
paint.setTextSize(20);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("Hello", 20, 20, paint);
}
}
and init it:
preview.addView(new CustomView(this));
There are few more smaller problems but it might get you going
Welcome guys,
I have problem with custom drawing view (Fingerprint)
I'm using
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
The problem is it draws black lines then it removes the drawing.
How to disable this black line and enable it to transparent
My code is:
import android.annotation.SuppressLint;
import android.graphics.PorterDuff;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.view.MotionEvent;
public class DrawingView extends View {
// drawing path
private Path drawPath;
// drawing and canvas paint
private Paint drawPaint, canvasPaint, drawCirclePaint;
// initial color
public int paintColor = Color.BLACK;
// canvas
private Canvas drawCanvas;
// canvas bitmap
private Bitmap canvasBitmap;
private float brushSize;
private boolean startedEditing = false;
private int width, height;
public boolean isLined = false;
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
public boolean isStartedEditing() {
return startedEditing;
}
public void setBackColor(int color) {
this.setBackgroundColor(color);
}
public int getBackColor() {
int colorID;
try {
ColorDrawable color = (ColorDrawable) this.getBackground();
colorID = color.getColor();
} catch (Exception e) {
colorID = Color.WHITE;
}
return colorID;
}
public void setupDrawing() {
brushSize = 4;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
drawPaint.setStrokeWidth(brushSize);
drawCirclePaint = new Paint();
drawCirclePaint.setColor(paintColor);
drawCirclePaint.setStyle(Paint.Style.FILL);
drawCirclePaint.setStrokeJoin(Paint.Join.ROUND);
drawCirclePaint.setStrokeCap(Paint.Cap.ROUND);
drawCirclePaint.setStrokeWidth(brushSize / 4);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
public void setBrushSize(float newSize) {
float pixelAmount = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, newSize, getResources()
.getDisplayMetrics());
brushSize = pixelAmount;
drawPaint.setStrokeWidth(brushSize);
}
public void setBrushColor(int newColor) {
drawPaint.setColor(newColor);
drawCirclePaint.setColor(newColor);
}
public int getBrushColor() {
return (drawPaint.getColor() == Color.WHITE) ? Color.BLACK : drawPaint
.getColor();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
width = w;
height = h;
// setLinedBackground();
}
#SuppressLint("NewApi")
public void setLinedBackground(boolean setOrRemove) {
if (setOrRemove) {
isLined = true;
// Lined Background
// Initialize lined background
Bitmap linedBackground = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas linedBackgroundCanvas = new Canvas(linedBackground);
// Set back white color
linedBackgroundCanvas.drawColor(Color.WHITE);
final float scale = DrawingView.this.getResources()
.getDisplayMetrics().density;
int pixels = (int) (50 * scale + 0.5f);
for (int i = 1, j = 0; j < drawCanvas.getHeight() / (pixels); i++, j++) {
Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
myPaint.setStrokeWidth((int) (1 * scale + 0.5f));
myPaint.setColor(Color.argb(60, 168, 168, 168));
linedBackgroundCanvas.drawLine(5, i * pixels,
drawCanvas.getWidth() - 5, i * pixels, myPaint);
}
BitmapDrawable ob = new BitmapDrawable(
DrawingView.this.getResources(), linedBackground);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
this.setBackgroundDrawable(ob);
} else {
this.setBackground(ob);
}
} else {
isLined = false;
// Lined Background
// Initialize lined background
setBackColor(Color.WHITE);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
AddDrawingNote.moreLayout.setVisibility(View.GONE);
startedEditing = true;
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawCanvas.drawPoint(touchX, touchY, drawCirclePaint);
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
public void setErase() {
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
}
and the xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/drawingnote_main_layout_bg"
android:orientation="vertical"
android:weightSum="100" >
<ImageView
android:id="#+id/drawingView_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="1dp"
android:background="#FFFF00"/>
<ibrahim.radwan.qnotes.DrawingView
android:id="#+id/add_drawing_note_drawing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="1dp"
android:background="#00ffffff" />
</RelativeLayout>
Any ideas :)
Yo, I figured this out. Just set the paint color to the background of your view.
I would like each time I press one of the buttons the rectangles on the screen to change position. Or the entire SurfaceView to refresh.
The app seems to run but the rectangles do not change position with the counter.
Thank you very much.
Hare is the xml code:
<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" >
<SurfaceView
android:id="#+id/surface"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
tools:context=".MainActivity" />
<Button
android:id="#+id/l"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:text="L" />
<Button
android:id="#+id/r"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:text="R" />
</RelativeLayout>
Here is the Java:
package com.example.rectangle;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
DrawView drawView;
Paint paint = new Paint();
int w, h, edge, axis_w;
int counter;
Button add, sub;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.r);
sub = (Button) findViewById(R.id.l);
display = (TextView) findViewById(R.id.textView1);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter += 10;
display.setText("Total is" + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter -= 10;
display.setText("Total is" + counter);
}
});
SurfaceView surface = (SurfaceView) findViewById(R.id.surface);
surface.getHolder().addCallback(new Callback() {
public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = holder.lockCanvas();
w = canvas.getWidth();
h = canvas.getHeight();
edge = 5;
axis_w = 3;
// canvas.drawRect(left, top, right, bottom, paint)
// Background
paint.setColor(Color.rgb(255, 255, 255));
canvas.drawRect(0, 0, w, h, paint);
// Canvas Background Color
paint.setColor(Color.rgb(0, 206, 209));
// Borders
canvas.drawRect(0, 0, w, edge, paint);
canvas.drawRect(0, h - edge, w, h, paint);
canvas.drawRect(0, 0, edge, h, paint);
canvas.drawRect(w - edge, 0, w, h, paint);
// Axis
canvas.drawRect(((w - axis_w) / 2) + counter, 0,
((w + axis_w) / 2) + counter, h, paint);
canvas.drawRect(0, (h - axis_w) / 2, w, (h + axis_w) / 2, paint);
holder.unlockCanvasAndPost(canvas);
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
}
}
Ok. Try Another solution. Try to make your own View class where you will draw your rectangle. I have prepared some code for you. Customize it to your needs.
Simlpe XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainL"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MainActivity"
android:id="#+id/button"
/>
</LinearLayout>
and java code
public class MainActivity extends Activity
{
MyRectg myRectg;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myRectg = new MyRectg(this);
((LinearLayout)findViewById(R.id.mainL)).addView(myRectg);
((Button)findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
myRectg.invalidate();
}
});
}
public class MyRectg extends View
{
public MyRectg(Context c)
{
super(c);
}
#Override
public void onDraw(Canvas c)
{
//this simulate new positions calculating
Random rnd = new Random();
Paint p = new Paint();
p.setColor(Color.GREEN);
c.drawRect(rnd.nextFloat()*100, rnd.nextFloat()*500, rnd.nextFloat()*300, rnd.nextFloat()*500, p);
}
}
Now canvas randomly moves when you click the button. Is this what you wanted?
Try to call Invalidate method on SurfaceView to refresh it after each position change.
EDIT:
And move position calculation from surfaceCreated to surfaceChanged method.
Currently on a view I have a ImageView and A custom class that draws a circle on the view. It will draw the circle on the view but it is hidden behind the image view. I know its there because when the radius is big enough I can see a small section that isn't behind the imageview. What code would bring it to the front?
EDIT: Found out that the above issue is not the problem. It seems that it is only drawing it on the portion that is reserved for the seekbar I have on the view?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_process);
mDraw = new Draw(this);
addContentView(mDraw, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
b = (Button) findViewById(R.id.button1);
seekBar1.setMax(500);
seekBar1.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
mDraw.setCords(500, 500, seekBar1.getProgress());
}
public void onStartTrackingTouch(SeekBar seekBar) {
mDraw.setCords(500, 500, seekBar1.getProgress());
}
public void onStopTrackingTouch(SeekBar seekBar) {
mDraw.setCords(500, 500, seekBar1.getProgress());
}
});
}
Here is the Draw class:
package org.DTS.boltsize;
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 Draw extends View {
private int x = 1;
private int y = 1;
private int r = 1;
public Draw(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void setCords(int mx, int my, int mr ){
x = mx;
y = my;
r = mr;
}
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
System.out.println("Drew :)");
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawCircle(x, y, r, paint);
super.onDraw(canvas);
}
public void DrawCirlce(Canvas canvas, int x, int y, int r){
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
canvas.drawCircle(x, y, r, paint);
super.onDraw(canvas);
}
}
Here is what it looks like. That red circle should cover the entire screen.
I would draw to a seperate bitmap that you have in a different imageView in the same space as your curent bitmap possibly in a FrameLayout. You can then use .bringToFront to decide the z order.
Solved by converting source to bitmap, then drawing a circle on that bitmap and sending that final bitmap to the imageview.