Search Results

Search found 104 results on 5 pages for 'ondraw'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • How to retain canvas state and use it in onDraw() method

    - by marqss
    I want to make a measure tape component for my app. It should look something like this with values from 0cm to 1000cm: Initially I created long bitmap image with repeated tape background. I drew that image to canvas in onDraw() method of my TapeView (extended ImageView). Then I drew a set of numbers with drawText() on top of the canvas. public TapeView(Context context, AttributeSet attrs){ ImageView imageView = new ImageView(mContext); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); imageView.setLayoutParams(params); mBitmap = createTapeBitmap(); imageView.setImageBitmap(mBitmap); this.addView(imageView); } private Bitmap createTapeBitmap(){ Bitmap mBitmap = Bitmap.createBitmap(5000, 100, Config.ARGB_8888); //size of the tape Bitmap tape = BitmapFactory.decodeResource(getResources(),R.drawable.tape);//the image size is 100x100px Bitmap scaledTape = Bitmap.createScaledBitmap(tape, 100, 100, false); Canvas c = new Canvas(mBitmap); Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setFakeBoldText(true); paint.setAntiAlias(true); paint.setTextSize(30); for(int i=0; i<=500; i++){ //draw background image c.drawBitmap(scaledTape,(i * 200), 0, null); //draw number in the middle of that background String text = String.valueOf(i); int textWidth = (int) paint.measureText(text); int position = (i * 100) + 100 - (textWidth / 2); c.drawText(text, position, 20, paint); } return mBitmap; } Finally I added this view to HorizontalScrollView. At the beginning everything worked beautifully but I realised that the app uses a Lot of memory and sometimes crashed with OutOfMemory exception. It was obvious because a size of the bitmap image was ~4mb! In order to increase the performance, instead of creating the bitmap I use Drawable (with the yellow tape strip) and set the tile mode to REPEAT: setTileModeX(TileMode.REPEAT); The view now is very light but I cannot figure out how to add numbers. There are too many of them to redraw them each time the onDraw method is called. Is there any way that I can draw these numbers on canvas and then save that canvas so it can be reused in onDraw() method?

    Read the article

  • Override onDraw to change how the drawing occurs (Android)

    - by Casebash
    I want to change how my UI elements display, so I am overriding onDraw. The following code allows me to change a View to be drawn using PorterDuff.Mode.DARKEN. Unfortunately, this method involves creating a bitmap the size of the entire screen, then drawing to it then drawing this large bitmap the main screen again, for each UI element. This isn't at all efficient. Is it possible to achieve this in a more effecient way? @Override protected void onDraw(Canvas canvas) { //TODO: Reduce the burden from multiple drawing Bitmap bitmap=Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.ARGB_8888); Log.e("tmp",canvas.getClipBounds().toString()); Canvas offscreen=new Canvas(bitmap); super.onDraw(offscreen); //Then draw onscreen Paint p=new Paint(); p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN)); canvas.drawBitmap(bitmap, 0, 0, p); }

    Read the article

  • Android View.onDraw() always has a clean Canvas

    - by CaseyB
    I am trying to draw an animation. To do so I have extended View and overridden the onDraw() method. What I would expect is that each time onDraw() is called the canvas would be in teh state that I left it in and I could choose to clear it or just draw over parts of it (This is how it worked when I used a SurfaceView) but each time the canvas comes back already cleared. Is there a way that I can not have it cleared? Or maybe save the previous state into a Bitmap so I can just draw that Bitmap and then draw over top of it?

    Read the article

  • Extended SurfaceView's onDraw() method never called

    - by Gab Royer
    Hi, I'm trying to modify the SurfaceView I use for doing a camera preview in order to display an overlaying square. However, the onDraw method of the extended SurfaceView is never called. Here is the source : public class CameraPreviewView extends SurfaceView { protected final Paint rectanglePaint = new Paint(); public CameraPreviewView(Context context, AttributeSet attrs) { super(context, attrs); rectanglePaint.setARGB(255, 200, 0, 0); rectanglePaint.setStyle(Paint.Style.FILL); rectanglePaint.setStrokeWidth(2); } @Override protected void onDraw(Canvas canvas){ canvas.drawRect(new Rect(10,10,200,200), rectanglePaint); Log.w(this.getClass().getName(), "On Draw Called"); } } public class CameraPreview extends Activity implements SurfaceHolder.Callback{ private SurfaceHolder holder; private Camera camera; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); // We remove the status bar, title bar and make the application fullscreen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // We set the content view to be the layout we made setContentView(R.layout.camera_preview); // We register the activity to handle the callbacks of the SurfaceView CameraPreviewView surfaceView = (CameraPreviewView) findViewById(R.id.camera_surface); holder = surfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Camera.Parameters params = camera.getParameters(); params.setPreviewSize(width, height); camera.setParameters(params); try { camera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } camera.startPreview(); } public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); } public void surfaceDestroyed(SurfaceHolder holder) { camera.stopPreview(); camera.release(); } }

    Read the article

  • Extended SurfaceView onDraw never called

    - by Gab Royer
    Hi, I'm trying to modify the SurfaceView I use for doing a camera preview in order to display an overlaying square. However, the onDraw method of the extended SurfaceView is never called. Here is the source : public class CameraPreviewView extends SurfaceView { protected final Paint rectanglePaint = new Paint(); public CameraPreviewView(Context context, AttributeSet attrs) { super(context, attrs); rectanglePaint.setARGB(255, 200, 0, 0); rectanglePaint.setStyle(Paint.Style.FILL); rectanglePaint.setStrokeWidth(2); } @Override protected void onDraw(Canvas canvas){ canvas.drawRect(new Rect(10,10,200,200), rectanglePaint); Log.w(this.getClass().getName(), "On Draw Called"); } } public class CameraPreview extends Activity implements SurfaceHolder.Callback{ private SurfaceHolder holder; private Camera camera; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); // We remove the status bar, title bar and make the application fullscreen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // We set the content view to be the layout we made setContentView(R.layout.camera_preview); // We register the activity to handle the callbacks of the SurfaceView CameraPreviewView surfaceView = (CameraPreviewView) findViewById(R.id.camera_surface); holder = surfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Camera.Parameters params = camera.getParameters(); params.setPreviewSize(width, height); camera.setParameters(params); try { camera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } camera.startPreview(); } public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); } public void surfaceDestroyed(SurfaceHolder holder) { camera.stopPreview(); camera.release(); } }

    Read the article

  • onDraw() triggered but results don't show

    - by Don
    I have the following routine in a subclass of view: It calculates an array of points that make up a line, then erases the previous lines, then draws the new lines (impact refers to the width in pixels drawn with multiple lines). The line is your basic bell curve, squeezed or stretched by variance and x-factor. Unfortunately, nothing shows on the screen. A previous version with drawPoint() and no array worked, and I've verified the array contents are being loaded correctly, and I can see that my onDraw() is being triggered. Any ideas why it might not be drawn? Thanks in advance! protected void drawNewLine( int maxx, int maxy, Canvas canvas, int impact, double variance, double xFactor, int color) { // impact = 2 to 8; xFactor between 4 and 20; variance between 0.2 and 5 double x = 0; double y = 0; int cx = maxx / 2; int cy = maxy / 2; int mu = cx; int index = 0; points[maxx<<1][1] = points[maxx<<1][0]; for (x = 0; x < maxx; x++) { points[index][1] = points[index][0]; points[index][0] = (float) x; Log.i(DEBUG_TAG, "x: " + x); index++; double root = 1.0 / (Math.sqrt(2 * Math.PI * variance)); double exponent = -1.0 * (Math.pow(((x - mu)/maxx*xFactor), 2) / (2 * variance)); double ePow = Math.exp(exponent); y = Math.round(cy * root * ePow); points[index][1] = points[index][0]; points[index][0] = (float) (maxy - y - OFFSET); index++; } points[maxx<<1][0] = (float) impact; for (int line = 0; line < points[maxx<<1][1]; line++) { for (int pt = 0; pt < (maxx<<1); pt++) { pointsToPaint[pt] = points[pt][1]; } for (int skip = 1; skip < (maxx<<1); skip = skip + 2) pointsToPaint[skip] = pointsToPaint[skip] + line; myLinePaint.setColor(Color.BLACK); canvas.drawLines(pointsToPaint, bLinePaint); // draw over old lines w/blk } for (int line = 0; line < points[maxx<<1][0]; line++) { for (int pt = 0; pt < maxx<<1; pt++) { pointsToPaint[pt] = points[pt][0]; } for (int skip = 1; skip < maxx<<1; skip = skip + 2) pointsToPaint[skip] = pointsToPaint[skip] + line; myLinePaint.setColor(color); canvas.drawLines(pointsToPaint, myLinePaint); / new color } } update: Replaced the drawLines() with drawPoint() in loop, still no joy for (int p = 0; p<pointsToPaint.length; p = p + 2) { Log.i(DEBUG_TAG, "x " + pointsToPaint[p] + " y " + pointsToPaint[p+1]); canvas.drawPoint(pointsToPaint[p], pointsToPaint[p+1], myLinePaint); } /// canvas.drawLines(pointsToPaint, myLinePaint);

    Read the article

  • Android draw using SurfaceView and Thread

    - by Morten Høgseth
    I am trying to draw a ball to my screen using 3 classes. I have read a little about this and I found a code snippet that works using the 3 classes on one page, Playing with graphics in Android I altered the code so that I have a ball that is moving and shifts direction when hitting the wall like the picture below (this is using the code in the link). Now I like to separate the classes into 3 different pages for not making everything so crowded, everything is set up the same way. Here are the 3 classes I have. BallActivity.java Ball.java BallThread.java package com.brick.breaker; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class BallActivity extends Activity { private Ball ball; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); ball = new Ball(this); setContentView(ball); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); setContentView(null); ball = null; finish(); } } package com.brick.breaker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Ball extends SurfaceView implements SurfaceHolder.Callback { private BallThread ballThread = null; private Bitmap bitmap; private float x, y; private float vx, vy; public Ball(Context context) { super(context); // TODO Auto-generated constructor stub bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball); x = 50.0f; y = 50.0f; vx = 10.0f; vy = 10.0f; getHolder().addCallback(this); ballThread = new BallThread(getHolder(), this); } protected void onDraw(Canvas canvas) { update(canvas); canvas.drawBitmap(bitmap, x, y, null); } public void update(Canvas canvas) { checkCollisions(canvas); x += vx; y += vy; } public void checkCollisions(Canvas canvas) { if(x - vx < 0) { vx = Math.abs(vx); } else if(x + vx > canvas.getWidth() - getBitmapWidth()) { vx = -Math.abs(vx); } if(y - vy < 0) { vy = Math.abs(vy); } else if(y + vy > canvas.getHeight() - getBitmapHeight()) { vy = -Math.abs(vy); } } public int getBitmapWidth() { if(bitmap != null) { return bitmap.getWidth(); } else { return 0; } } public int getBitmapHeight() { if(bitmap != null) { return bitmap.getHeight(); } else { return 0; } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub ballThread.setRunnable(true); ballThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub boolean retry = true; ballThread.setRunnable(false); while(retry) { try { ballThread.join(); retry = false; } catch(InterruptedException ie) { //Try again and again and again } break; } ballThread = null; } } package com.brick.breaker; import android.graphics.Canvas; import android.view.SurfaceHolder; public class BallThread extends Thread { private SurfaceHolder sh; private Ball ball; private Canvas canvas; private boolean run = false; public BallThread(SurfaceHolder _holder,Ball _ball) { sh = _holder; ball = _ball; } public void setRunnable(boolean _run) { run = _run; } public void run() { while(run) { canvas = null; try { canvas = sh.lockCanvas(null); synchronized(sh) { ball.onDraw(canvas); } } finally { if(canvas != null) { sh.unlockCanvasAndPost(canvas); } } } } public Canvas getCanvas() { if(canvas != null) { return canvas; } else { return null; } } } Here is a picture that shows the outcome of these classes. I've tried to figure this out but since I am pretty new to Android development I thought I could ask for help. Does any one know what is causing the ball to be draw like that? The code is pretty much the same as the one in the link and I have tried to experiment to find a solution but no luck. Thx in advance for any help=)

    Read the article

  • Clearing canvas with Canvas.drawColor()

    - by strangeInAStrangerLand
    I'm attempting to change the background image of a custom View with some success. The image will change but the problem is that I still see traces of the old image. When I attempt to clear the canvas before drawing the new image, it doesn't appear to work. I create a bitmap to store the image. When changing the image, I call Canvas.drawColor() before drawing the new image but the old image persists. I've tried drawColor(0), drawColor(Color.BLACK), c.drawColor(0, PorterDuff.Mode.CLEAR), and none of the above works. As such, I had to post this for review from more experienced minds than mine. The actual code is as follows: private int bgnd; private boolean switching; public void setBgnd(int incoming){ switching = true; switch (incoming){ case R.drawable.image1: bgnd = incoming; this.invalidate(); break; case R.drawable.image2: bgnd = incoming; this.invalidate(); break; } } protected void onDraw(Canvas c){ if(switching == true){ Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd); c.drawColor(0, PorterDuff.Mode.CLEAR); c.drawBitmap(b, 0, 0, null); switching = false; }else{ Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd); c.drawBitmap(b, 0, 0, null); } }

    Read the article

  • Call OnDraw in another method, then "refresh" that call in ANOTHER method.

    - by Aidan
    Hey guys, Hopefully this will actually make sense and sorry if its a stupid / obvious question. Basically I'm calling the onDraw method like so... requestWindowFeature(Window.FEATURE_NO_TITLE); Preview mPreview = new Preview(this); DrawOnTop mDraw = new DrawOnTop(this); setContentView(mPreview); addContentView(mDraw, new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); You see I'm drawing it on top of a Camera view and the information being drawn is subject to change. I have a listener setup which will update the variables being drawn at the appropriate time but I now want to "refresh" this draw in that listener. How would I do such a thing?

    Read the article

  • custom button: properties change, button should be redrawn

    - by Rutger
    Hi I'm developing an Android app. I have class derived from button to represent a special type of button. This special type has some properties (integers) and according to these one or more circles have to be drawn on top of the button. So I overrode the onDraw function, which looks the values up and accordingly draws the circles. But the class has a function to set new values for its properties. So new values are set but the changes are not reflected in the UI. It seems like the onDraw function is not called. When later I click the button or show a pop up message above my interface the onDraw function is called and the button is drawn correctly. So my question: when changing the properties how can I say that the button has to be redrawn? Thanks a lot!

    Read the article

  • How to rotate a drawable with anti-aliasing enabled

    - by Mike
    I need to rotate an ImageView by a few degrees. I'm doing this by subclassing ImageView and overloading onDraw() @Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.scale(0.92f,0.92f); canvas.translate(14, 0); canvas.rotate(1,0,0); super.onDraw(canvas); canvas.restore(); } The problem is that the image that results shows a bunch of jaggies. How can I antialias an ImageView that I need to rotate in order to eliminate jaggies? Is there a better way to do this?

    Read the article

  • can we use layout in Customview ?

    - by UMMA
    friends, i have a custom view class public class Zoom extends View { private Drawable image; private int zoomControler=20; public Zoom(Context context) { super(context); image=context.getResources().getDrawable(R.drawable.icon); setFocusable(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //TransparentPanel tp = new TransparentPanel(this.getContext()); //Button MyButton = new Button(this.getContext()); //MyButton.setText("Press me"); //tp.addView(MyButton); image.setBounds((getWidth()/2)-zoomControler, (getHeight()/2)-zoomControler, (getWidth()/2)+zoomControler, (getHeight()/2)+zoomControler); image.draw(canvas); } } can i use SetContentView(R.layout.mylayout) in this custom view to display that design? or how can i display button with image ondraw method as i have commented the code ? any help would be appreciated.

    Read the article

  • How to handle loading and keeping many bitmaps in an Android 2D game

    - by Lumis
    In an Android 2D game which is using SurfaceView where its onDraw is driven by a loop from a Thread, I use many bitmap sprites (sprite sheets) and two background size bitmaps, which are all loaded into memory at the start. It all works fine, however, when the activity is onPause or after reloading it few times, Android shows a tendency to wipe out the big bitmaps only, probably to free memory. Sometimes this happens even in the middle of loading this very activity. In order to counter this, I made a check in the onDraw method to test if the big bitmaps are still there and reload them if they are forcefully recycled by Android, before drawing them on Canvas. This solution may not be the most stable, and since I know that there are much more accomplished android game programmers here than myself, I hope you can reveal some tricks or secrets or at least provide some good hints, how to overcome this.

    Read the article

  • Drawing to the canvas

    - by Mattl
    I'm writing an android application that draws directly to the canvas on the onDraw event of a View. I'm drawing something that involves drawing each pixel individually, for this I use something like: for (int x = 0; x < xMax; x++) { for (int y = 0; y < yMax; y++){ MyColour = CalculateMyPoint(x, y); canvas.drawPoint(x, y, MyColour); } } The problem here is that this takes a long time to paint as the CalculateMyPoint routine is quite an expensive method. Is there a more efficient way of painting to the canvas, for example should I draw to a bitmap and then paint the whole bitmap to the canvas on the onDraw event? Or maybe evaluate my colours and fill in an array that the onDraw method can use to paint the canvas? Users of my application will be able to change parameters that affect the drawing on the canvas. This is incredibly slow at the moment.

    Read the article

  • Can I add a portrait layout on top of a landscape Camera SurfaceView?

    - by Uwe Krass
    My application should hold a camera preview surface. The camera is fixed to landscape view via AndroidMainfest.xml <application android:icon="@drawable/icon" android:label="Camera"> <uses-library android:name="com.google.android.maps" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <activity android:name=".CameraPreview" android:label="Camera" android:screenOrientation="landscape"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> If there is another way to get the camera preview itself to behave correctly, please let me know. Now I need to have an overlay that holds a bunch of buttons. Due to usability, the user interface should be set to portrait view (or even better orientation aware). Is there a way to have a transparent layout (for buttons and other GUI elements) in portrait orientation? I tried to write a special rotated layout by extending a RelativeLayout, but the onDraw method isn't called at anytime. public class RotatedOverlay extends RelativeLayout { private static final String TAG = "RotatedOverlay"; public RotatedOverlay(Context context, AttributeSet attrs ) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { canvas.rotate(90); super.onDraw(canvas); } I am quite new to the Android plattform programming. Of course I dont know much about the programming tricks and workarounds yet. I did a lot of research over the last two weeks (even studied the native Camera implementation), but couldnt find a good solution so far. Maybe it works with two seperate Activities, but I dont think, that this can the right solution.

    Read the article

  • Android Game Development problem with Speed = Distance / Time

    - by Charlton Santana
    I have been coding speed for an object. I have made it so the object will move from one end of the screen to another at a speed depending on the screen size, at the monemt I have made it so it will take one second to pass the screen. So i have worked out the speed in code but when I go to assign the speed it tells me to force close and i do not understand why. Here is the code: MainGame Code: @Override protected void onDraw(Canvas canvas) { setBlockSpeed(getWidth()); } private int blockSpeed; private void setBlockSpeed(int screenWidth){ Log.d(TAG, "screenWidth " + screenWidth); blockSpeed = screenWidth / 100; // 100 is the FPS.. i want it to take 1 second to pass the screen Math.round(blockSpeed); // to make it a whole number block.speed = blockSpeed; // this is line 318!! if i put eg block.speed = 8; it still tells me to force close } Block.java Code: public int speed; public void draw(Canvas canvas) { canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null); if(dontmove == 0){ this.x -= speed; // if it was eg this.x -= 18; it would not have an error } } The exception 06-08 13:22:34.315: E/AndroidRuntime(2801): FATAL EXCEPTION: Thread-11 06-08 13:22:34.315: E/AndroidRuntime(2801): java.lang.NullPointerException 06-08 13:22:34.315: E/AndroidRuntime(2801): at com.charltonsantana.game.MainGame.setBlockSpeed(MainGame.java:318) 06-08 13:22:34.315: E/AndroidRuntime(2801): at com.charltonsantana.game.MainGame.onDraw(MainGame.java:351) 06-08 13:22:34.315: E/AndroidRuntime(2801): at com.charltonsantana.game.MainThread.run(MainThread.java:64)

    Read the article

  • Algorithm to zoom a plotted function

    - by astinx
    I'm making a game in android and I need plot a function, my algorithm is this: @Override protected void onDraw(Canvas canvas) { float e = 0.5f; //from -x axis to +x evaluate f(x) for (float x = -z(canvas.getWidth()); x < z(canvas.getWidth()); x+=e) { float x1,y1; x1 = x; y1 = f(x); canvas.drawPoint((canvas.getWidth()/2)+x1, (canvas.getHeight()/2)-y1, paintWhite); } super.onDraw(canvas); } This is how it works. If my function is, for example f(x)=x^2, then z(x) is sqrt(x). I evaluate each point between -z(x) to z(x) and then I draw them. As you can see I use the half of the size of the screen to put the function in the middle of the screen. The problem isn't that the code isn't working, actually plots the function. But if the screen is of 320*480 then this function will be really tiny like in the image below. My question is: how can I change this algorithm to scale the function?. BTW what I'm really wanting to do is trace a route to later display an animated sprite, so actually scale this image doesnt gonna help me. I need change the algorithm in order to draw the same interval but in a larger space. Any tip helps, thanks! Current working result Desired result UPDATE: I will try explain more in detail what the problem is. Given this interval [-15...15] (-z(x) to z(x)) I need divide this points in a bigger interval [-320...320] (-x to x). For example, when you use some plotting software like this one. Although the div where is contain the function has 640 px of width, you dont see that the interval is from -320 to 320, you see that the interval is from -6 to 6. How can I achieve this?

    Read the article

  • Weird y offset when using custom frag shader (Cocos2d-x)

    - by Mister Guacamole
    I'm trying to mask a sprite so I wrote a simple fragment shader that renders only the pixels that are not hidden under another texture (the mask). The problem is that it seems my texture has its y-coordinate offset after passing through the shader. This is the init method of the sprite (GroundZone) I want to mask: bool GroundZone::initWithSize(Size size) { // [...] // Setup the mask of the sprite m_mask = RenderTexture::create(textureWidth, textureHeight); m_mask->retain(); m_mask->setKeepMatrix(true); Texture2D *maskTexture = m_mask->getSprite()->getTexture(); maskTexture->setAliasTexParameters(); // Disable linear interpolation on the mask // Load the custom frag shader with a default vert shader as the sprite’s program FileUtils *fileUtils = FileUtils::getInstance(); string vertexSource = ccPositionTextureA8Color_vert; string fragmentSource = fileUtils->getStringFromFile( fileUtils->fullPathForFilename("CustomShader_AlphaMask_frag.fsh")); GLProgram *shader = new GLProgram; shader->initWithByteArrays(vertexSource.c_str(), fragmentSource.c_str()); shader->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); shader->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); shader->link(); CHECK_GL_ERROR_DEBUG(); shader->updateUniforms(); CHECK_GL_ERROR_DEBUG(); int maskTexUniformLoc = shader->getUniformLocationForName("u_alphaMaskTexture"); shader->setUniformLocationWith1i(maskTexUniformLoc, 1); this->setShaderProgram(shader); shader->release(); // [...] } These are the custom drawing methods for actually drawing the mask over the sprite: You need to know that m_mask is modified externally by another class, the onDraw() method only render it. void GroundZone::draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated) { m_renderCommand.init(_globalZOrder); m_renderCommand.func = CC_CALLBACK_0(GroundZone::onDraw, this, transform, transformUpdated); renderer->addCommand(&m_renderCommand); Sprite::draw(renderer, transform, transformUpdated); } void GroundZone::onDraw(const kmMat4 &transform, bool transformUpdated) { GLProgram *shader = this->getShaderProgram(); shader->use(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_mask->getSprite()->getTexture()->getName()); glActiveTexture(GL_TEXTURE0); } Below is the method (located in another class, GroundLayer) that modify the mask by drawing a line from point start to point end. Both points are in Cocos2d coordinates (Point (0,0) is down-left). void GroundLayer::drawTunnel(Point start, Point end) { // To dig a line, we need first to get the texture of the zone we will be digging into. Then we get the // relative position of the start and end point in the zone's node space. Finally we use the custom shader to // draw a mask over the existing texture. for (auto it = _children.begin(); it != _children.end(); it++) { GroundZone *zone = static_cast<GroundZone *>(*it); Point nodeStart = zone->convertToNodeSpace(start); Point nodeEnd = zone->convertToNodeSpace(end); // Now that we have our two points converted to node space, it's easy to draw a mask that contains a line // going from the start point to the end point and that is then applied over the current texture. Size groundZoneSize = zone->getContentSize(); RenderTexture *rt = zone->getMask(); rt->begin(); { // Draw a line going from start and going to end in the texture, the line will act as a mask over the // existing texture DrawNode *line = DrawNode::create(); line->retain(); line->drawSegment(nodeStart, nodeEnd, 20, Color4F::RED); line->visit(); } rt->end(); } } Finally, here's the custom shader I wrote. #ifdef GL_ES precision mediump float; #endif varying vec2 v_texCoord; uniform sampler2D u_texture; uniform sampler2D u_alphaMaskTexture; void main() { float maskAlpha = texture2D(u_alphaMaskTexture, v_texCoord).a; float texAlpha = texture2D(u_texture, v_texCoord).a; float blendAlpha = (1.0 - maskAlpha) * texAlpha; // Show only where mask is invisible vec3 texColor = texture2D(u_texture, v_texCoord).rgb; gl_FragColor = vec4(texColor, blendAlpha); return; } I got a problem with the y coordinates. Indeed, it seems that once it has passed through my custom shader, the sprite's texture is not at the right place: Without custom shader (the sprite is the brown thing): With custom shader: What's going on here? Thanks :) EDIT It looks like after passing through the shader when I set the position of the sprite I set it in points, with (0,0) being in the top-right. Indeed, when I do sprite->setPosition(320, 480), the sprite is perfectly placed at the top of the screen.

    Read the article

  • Exceptions silently caught by Windows, how to handle manually?

    - by Mark Ingram
    We're having problems with Windows silently eating exceptions and allowing the application to continue running, when the exception is thrown inside the message pump. For example, we created a test MFC MDI application, and overrode OnDraw: void CTestView::OnDraw(CDC* /*pDC*/) { *(int*)0 = 0; // Crash CTestDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } You would expect a nasty error message when running the application, but you actually get nothing at all. The program appears to be running perfectly well, but if you check the output window you will see: First-chance exception at 0x13929384 in Test.exe: 0xC0000005: Access violation writing location 0x00000000. First-chance exception at 0x77c6ee42 in Test.exe: 0xC0150010: The activation context being deactivated is not active for the current thread of execution. I know why I'm receiving the application context exception, but why is it being handled silently? It means our applications could be suffering serious problems when in use, but we'll never know about it, because our users will never report any problems.

    Read the article

  • change view with onSensorChanged result

    - by tipu
    I have a view, set by setContentView(new CompassView(this)); I have the onDraw and update methods filled out. What I need to do with the view CompassView is update my view with the new data at the end of the call in the onSensorChanged method. The methods I have to fill out, I believe, are the surfaceChanged and surfaceCreated. They are normally using threads which takes care of the update and onDraw calls but I removed the thread because when the thread was enabled, in the infinite while loop I was never getting any azimuth value what so ever.

    Read the article

  • Adding GestureOverlayView to my SurfaceView class, how to add to view hierarchy?

    - by Codejoy
    I was informed in a later answer that I have to add the GestureOverlayView I create in code to my view hierarchy, and I am not 100% how to do that. Below is the original question for completeness. I want my game to be able to recognize gestures. I have this nice SurfaceView class that I do an onDraw to draw my sprites, and I have a thread thats running it to call the onDraw etc . This all works great. I am trying to add the GestureOverlayView to this and it just isn't working. Finally hacked to where it doesn't crash but this is what i have public class Panel extends SurfaceView implements SurfaceHolder.Callback, OnGesturePerformedListener { public Panel(Context context) { theContext=context; mLibrary = GestureLibraries.fromRawResource(context, R.raw.myspells); GestureOverlayView gestures = new GestureOverlayView(theContext); gestures.setOrientation(gestures.ORIENTATION_VERTICAL); gestures.setEventsInterceptionEnabled(true); gestures.setGestureStrokeType(gestures.GESTURE_STROKE_TYPE_MULTIPLE); gestures.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); //GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.addOnGesturePerformedListener(this); } ... ... onDraw... surfaceCreated(..); ... ... public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { ArrayList<Prediction> predictions = mLibrary.recognize(gesture); // We want at least one prediction if (predictions.size() > 0) { Prediction prediction = predictions.get(0); // We want at least some confidence in the result if (prediction.score > 1.0) { // Show the spell Toast.makeText(theContext, prediction.name, Toast.LENGTH_SHORT).show(); } } } } The onGesturePerformed is never called. Their example has the GestureOverlay in the xml, I am not using that, my activity is simple: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); Panel p = new Panel(this); setContentView(p); } So I am at a bit of a loss of the missing piece of information here, it doesn't call the onGesturePerformed and the nice pretty yellow "you are drawing a gesture" never shows up.

    Read the article

  • How does ImageView just redraw part of its content when invalidate(Rect) is called?

    - by imax366
    Hi, guys I am new to Android development, just reading docs and trying the APIs. I am quit confused how ImageView managed to draw just a part of its content after an invalidate(Rect) invocation. I've checked ImageView.java, found no other drawing method except onDraw(Canvas), but onDraw(Canvas) only cut the drawable only if it is beyound the view's visible boundary. I also read the implementation of View.invalidate(Rect), I think the key of this function is calling to mParent.invalidateChild(this, r); However, I think the parent view doesn't know how to draw the child in the given Rect, it finally has to call some method of it child to paint out. Has anybody investigated this part of codes? Would you please give me some guide?

    Read the article

  • referencing ints from other classes

    - by user357032
    if i wanted to reference an int from another class how would i go about doing that??? public class Zoom extends View { private Drawable image; public int zoomControler=20; public Zoom(Context context) { super(context); image=context.getResources().getDrawable(R.drawable.icon); setFocusable(true); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); image.setBounds((getWidth()/2)-zoomControler, (getHeight()/2)-zoomControler, (getWidth()/2)+zoomControler, (getHeight()/2)+zoomControler); image.draw(canvas); } } class HelloOnTouchListener implements OnTouchListener{ @Override public boolean onTouch(View arg0, MotionEvent arg1) { return true; } } in this case i want to reference the zoomControler from the first class in the second helloontouchlistener class

    Read the article

  • Drag and drop + custom drawing in Android

    - by Rich
    I am working on something that needed custom drag-and-drop functionality, so I have been subclassing View, doing a bunch of math in response to touch events, and then rendering everything manually through code on the canvas in onDraw. Now, the more functionality I add, the more the code is growing out of control and I find myself writing a ton more code than I would expect to write in a high level environment like Android. Is this how it's done, or am I missing something? If I'm not doing anything fancy in the UI, the framework handles the majority of my interactions. Built-in controls handle the touches and drags, and my code is pretty much limited to business logic and data. Is there a way to leverage the power of some of the UI controls and things like animations while also doing some of it manually in the onDraw canvas? Is there an accepted standard of when to use one or the other (if indeed the two approaches can be mixed)?

    Read the article

1 2 3 4 5  | Next Page >