I have a GridView. I would like each item to be an object derived form SurfaceView. I have created a class which extends SurfaceView, and an Adapter whose getView() returns an instance of this.
All I get is a little black square for each grid item. The SurfaceView's draw() is never called (shown by adding trace) and neither is its surfaceCreated().
How do I do this in a way which allows me to draw stuff on the SurfaceView please? I think the crux of the problem is that surfaceCreated() is never called. Why not?
This is my Adapter:
public class LevelAdapter extends BaseAdapter
{
...
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LevelNumberView number = new LevelNumberView(m_context);
number.setLayoutParams(new GridView.LayoutParams(70, 70));
number.setPadding(1, 1, 1, 1);
number.masDraw(); // Experiment - but it doesn't work
return number;
}
}
Then my SurfaceView class:
public class LevelNumberView extends SurfaceView
implements SurfaceHolder.Callback
{
...
#Override
public void surfaceCreated(SurfaceHolder holder)
{
m_surfaceHolder = holder;
}
#Override
public void draw(Canvas canvas)
{
Log.i("LevelNumberView","Draw");
doDraw(canvas, Color.YELLOW);
}
public void masDraw()
{
Log.i("LevelNumberView","masDraw");
if (null != m_surfaceHolder)
{
Canvas canvas = m_surfaceHolder.lockCanvas();
if (null != canvas)
{
doDraw(canvas, Color.GREEN);
m_surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
private void doDraw(Canvas canvas, int colour)
{
int w = canvas.getWidth();
int h = canvas.getHeight();
int min = Math.min(w,h);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(colour);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(w/2, h/2, min, paint);
}
}
Thanks!
-Mark
Overriding draw() probably isn't what you want. If you want to draw on the View, override onDraw(). If you want to draw on the Surface, that's usually done from a separate thread. (The SurfaceView has two parts; the surface part is a completely separate layer that is drawn behind the layer with the View-based UI.)
If you haven't called SurfaceHolder().addCallback(), no object will be receiving callbacks -- the SurfaceView doesn't send callbacks to itself, so subclassing SurfaceView doesn't really do much for you.
Perhaps what you want is simply a custom View?
Related
I wrote the following code and it works well. But I have other purpose. I want to click only on a view to doing the operations.First, Please see the following image:
MY CODE IS AS FOLLOWS:
public class MainActivity extends Activity {
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle bundle)
{ super.onCreate(bundle);
relativeLayout = new RelativeLayout(getApplicationContext());
setContentView(relativeLayout);
A a = new A(this);
relativeLayout.addView(a);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
B b = new B(getApplicationContext());
relativeLayout.addView(b);
}
});
}
}
class A extends View {
Paint paint;
A(Context context) {
super(context);
paint = new Paint();
}
#Override
protected void onDraw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setColor(Color.RED);
canvas.drawRect(20,60,100,150,paint);
}
}
class B extends View {
Paint paint;
B(Context context){
super(context);
paint = new Paint();
}
#Override
protected void onDraw(Canvas canvas){
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
canvas.drawRect(100,150,200,250,paint);
}
}
when I run the above code I can see the green rectangle after press on the red rectangle. But the problem is that when I press another places on the screen I can do this operations also. I want that only I can see the green rectangle to press on the red rectangle and not in the another places on the screen to doing this operations.
Use onTouch event
a.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getX(0)>=20 && event.getY(0)>=60 && event.getX(0)<=160 && event.getY(0)<=150) {
B b = new B(getApplicationContext());
relativeLayout.addView(b);
}
return true;
}
});
You are defining the red square's parameters but not the parameters of the canvas in which you are drawing. You are creating the view (A) without defining the width and height of it, so it is set to match_parent by default, which means it will take the whole size of your RelativeLayout (the whole screen). So, when you click "outside" the red square you are actually clicking the view (A).
Try to define an specific height and width for the view in which you are drawing, like this.
A a = new A(this);
a.setLayoutParams(new RelativeLayout.LayoutParams(300,300));
Remember that LayoutParams takes pixels as parameters, so you should really convert the dps to px as specified here
Also, setting some background colors to your views (relativeLayout, A) will help you visualize what you are doing.
# nukeforum, your guess helped me very much. I thank all of you. My problem was exactly from the canvas and its size. I added the following operation in my code and solved my problem.
relativeLayout.addView(a,70,70);
For A class, I changed as follows:
canvas.drawRect(10,20,30,40,paint);
I've just started playing around with developing an Android app and have run into some troubles.
The intention of this testing app is to draw a square to the screen that moves towards the bottom right of the screen. Simple as that.
MainActivity class (current entry point) looks like so:
Main Activity class (current entry point) looks like so:
public class MainActivity extends Activity {
Canvas canvas;
GameLoopThread gameThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //Super constructor
gameThread=new GameLoopThread(); //Create GameLoop instance
//Create mySurfaceView instance and pass it the new gameloop
MySurfaceView sView=new MySurfaceView(this,gameThread);
//Without this only the bit I cant remove is drawn
sView.setBackgroundColor(Color.TRANSPARENT);
setContentView(sView); //Set the current ContentView to the one we created
//Pass the GameThread the MySurfaceView to repeatedly update
gameThread.setSurfaceView(sView);
gameThread.start(); //Start the thread
}
}
GameLoopThread looks like so:
public class GameLoopThread extends Thread {
protected volatile boolean running;
private MySurfaceView view;
public GameLoopThread(){
}
public void setSurfaceView(MySurfaceView view){
this.view=view;
}
#Override
public void run() {
running=true;
while(running){
Canvas c = null;
c = view.getHolder().lockCanvas(); //Get the canvas
if (c!=null) {
synchronized (view) {
view.draw(c); //Run the doDraw method in our MySurfaceView
}
}
try {
sleep(30, 0); //Throttle
}
catch(InterruptedException e){
e.printStackTrace();
}
if (c != null) {
view.getHolder().unlockCanvasAndPost(c); //Lock and post canvas
}
}
}
public void terminate(){
running=false;
}
}
And finally MySurfaceView looks like so:
public class MySurfaceView extends SurfaceView {
private Bitmap bmp;
private SurfaceHolder holder;
private final GameLoopThread gameLoop;
Paint paint;
float x=0;
float y=0;
public MySurfaceView(Context c, GameLoopThread gThread){
super(c);
holder=getHolder();
gameLoop=gThread;
paint=new Paint();
paint.setColor(Color.CYAN);
paint.setStrokeWidth(10);
holder.addCallback(new CallBack());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
paint.setColor(paint.getColor() - 1);
canvas.drawRect(x, y, x + 50, y + 50, paint);
x++;
y++;
}
private class CallBack implements SurfaceHolder.Callback{
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoop.terminate();
while (true) {
try {
gameLoop.join();
break;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
}
}
The Issue
This all works, except that one of the initial few draws to the view "sticks". It remains over top of anything drawn at a later date. See below:
I cannot fathom why this is happening. No amount of clearing fixes the problem. If I stop drawing the 'new' square the 'stuck' square remains. You can see I'm varying the color of the 'new' square to test if it changes the 'stuck' one which would indicate it was being redraw. Clearly it isn't.
Drawing nothing for around 4 loops with a 30ms pause in between each draw results in no 'stuck' square. Starting drawing after those initial 4 results in a square that moves across the screen as it should.
Varying the pause time changes how many loops must be waited, but the relationship doesn't appear to be proportional.
Other Info
This is being run on a Samsung Galaxy SIII Mini
SDK verson 4.0.3
A SurfaceView has two parts, a Surface and a View. When you get a Canvas with lockCanvas(), you're getting a Canvas for the Surface part. The Surface is a separate layer, independent of the layer used for all of the View elements.
You've subclassed SurfaceView and provided an onDraw() function, which the View hierarchy uses to render onto the View portion. My guess is that the View hierachy gets an invalidate and decides to draw on the View part of the SurfaceView. Your experiment of skipping the rendering for the first few loop iterations works because you're skipping the render that happens on the invalidate. Because the Surface layer is drawn behind the View layer, you see the onDraw()-rendered square on top of the other stuff you're rendering.
Normally you don't draw on the View; it's just a transparent place-holder, used by the layout code to leave a "hole" in the View layer where the Surface will show through.
Rename onDraw() to doDraw(), and drop the #override. I don't think there's a reason to subclass SurfaceView at all. That should prevent the SurfaceView from drawing on its View.
Of course, if you want to have a mask layer, perhaps to add rounded corners or a "dirt" effect, drawing on the View is an easy way to accomplish it.
See the Graphics Architecture doc for the full story.
Trying to redraw on canvas when tab is selected:
#Override
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setSelected(false); //unselected
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setSelected(true); // selected
}
Then on the custom view i do:
public class TabIndicator extends LinearLayout {
...
public void setSelectedTab(boolean isSelected){
this.isSelected = isSelected;
if(isSelected){
this.invalidate();
this.postInvalidate();
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(isSelectedTab()){
Paint paint2 = new Paint();
Path path2 = new Path();
paint2.setStyle(Paint.Style.STROKE);
paint2.setStrokeWidth(10);
paint2.setColor(Color.parseColor(getResources().getString(R.string.NAVY_BLUE)));
path2.moveTo(width*(1/4f), height);
path2.lineTo(width*(3/4f), height);
path2.close();
canvas.drawPath(path2, paint2);
}
}
Nothing happens even though draw is called repeatedly. (Checked via log.d)
It only draws the first time when the Layout is created.
You are extending a ViewGroup
http://developer.android.com/reference/android/view/ViewGroup.html
By default, onDraw() isn't called for ViewGroup objects. Instead, you can override dispatchDraw().
Alternatively, you can enable ViewGroup drawing by calling setWillNotDrawEnabled(false) in your constructor.
https://groups.google.com/forum/?fromgroups#!topic/android-developers/oLccWfszuUo
Check Romain Guy's comment
I could find a link for a similar question i answered before. Has an example do check the link below
onDraw method not called in my application
I'm trying to apply a visual effect to a viewgroup. My idea is to grab a bitmap of the viewgroup, shrink it down, expand it back up, and draw it over the viewgroup to give it a blocky, low quality effect.
I've got most of the way there using this code:
public class Blocker {
private static final float RESAMPLE_QUALITY = 0.66f; // less than 1, lower = worse quality
public static void block(Canvas canvas, Bitmap bitmap_old) {
block(canvas, bitmap_old, RESAMPLE_QUALITY);
}
public static void block(Canvas canvas, Bitmap bitmap_old, float quality) {
Bitmap bitmap_new = Bitmap.createScaledBitmap(bitmap_old, Math.round(bitmap_old.getWidth() * RESAMPLE_QUALITY), Math.round(bitmap_old.getHeight() * RESAMPLE_QUALITY), true);
Rect from = new Rect(0, 0, bitmap_new.getWidth(), bitmap_new.getHeight());
RectF to = new RectF(0, 0, bitmap_old.getWidth(), bitmap_old.getHeight());
canvas.drawBitmap(bitmap_new, from, to, null);
}
}
I simply pass in the canvas to draw on and a bitmap of what needs to be scaled down+up and it works well.
public class BlockedLinearLayout extends LinearLayout {
private static final String TAG = BlockedLinearLayout.class.getSimpleName();
public BlockedLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomAttributes(context, attrs);
setup();
}
public BlockedLinearLayout(Context context) {
super(context);
setup();
}
private void setup() {
this.setDrawingCacheEnabled(true);
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// block(canvas); If I call this here, it works but no updates
}
#Override
public void onDraw(Canvas canvas) {
// block(canvas); If I call this here, draws behind children, still no updates
}
private void block(Canvas canvas) {
Blocker.block(canvas, this.getDrawingCache());
}
}
The problem I'm having is in my viewgroup. If I run the block method in the viewgroup's draw, it draws over everything but doesn't ever update when child views change. I've traced function calls with Log, and the draw method seems to be running, but nothing changes.
I've also tried implementing this in onDraw. This draws the bitmap behind all the children views, and again they aren't updating.
Can anyone explain how I would go about fixing this?
Try this:
#Override
protected void dispatchDraw(Canvas canvas) {
// call block() here if you want to draw behind children
super.dispatchDraw(canvas);
// call block() here if you want to draw over children
}
And call destroyDrawingCache() and then, buildDrawingCache() each time you change a child.
Draw() method will work well for you.
I'm now trying to make a count time view in a circle shape, when time is passing, the view will reducing his angle. It's used to cover profile photo(a circle shape photo).
Starting with Android API 23, you can use onDrawForeground(Canvas) to draw on top of child views: https://developer.android.com/reference/android/view/View#onDrawForeground(android.graphics.Canvas)
Unlike onDraw() though, be sure to call through to the super class:
#Override
public void onDrawForeground(final Canvas canvas) {
super.onDrawForeground(canvas);
// Your code here
}
My project is about image processing in android.I have a bitmap that I have loaded from a resource file (an PNG image). I want to draw it. But I couldn't.
Here my code snippet:
mB = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
Canvas c = new Canvas(mB);
Paint p = new Paint();
c.drawBitmap(mB,0,0,p);
it didn't work. Is the code true? .Is there any thing more that I must do?
You should use an ImageView instead and load it by
imageView.setImageResource(R.drawable.picture);
If you want to manually draw it with a Canvas, you have to use a canvas that is passed into a draw() method and implement a Custom View.
Update to add example CustomView:
public class CustomView extends View {
private Paint mPaint;
private Drawable mDrawable;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mDrawable = context.getResources().getDrawable(R.drawable.some_drawable);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mDrawable.draw(canvas);
}
}
There are a couple of things you are missing.
First, I think you're misunderstanding the Canvas(Bitmap b) constructor. The Bitmap passed in there is one that the Canvas will draw into. This could be just a new Bitmap that you constructed.
Second, it is recommended that you use the Canvas that is passed to you in your View's onDraw method. Presumably that View is one from your Activity, either fetched from your XML layout via findViewById or constructed and passed to setContentView in the Activity's onCreate() method.
So, you are going to have to subclass View and override the onDraw method to get your drawing done. Something like:
public class MyView extends View {
#Override
public void onDraw (Canvas c) {
Bitmap mB = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.picture);
c.drawBitmap(mB, 0, 0, null);
}
}
Then, in your Activity, you'll need to create an instance of your new View and pass it to the Activity via setContentView:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mv = new MyView(this);
setContentView(mv);
}
You can instead call the setContentView(View v, ViewGroup.LayoutParameters lp) overload if you want to set up the LayoutParameters.
I haven't tested any of this, but it should at least get you on the right path.