Search Results

Search found 1375 results on 55 pages for 'bitmap'.

Page 23/55 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • multi-dimension array problem in RGSS (RPG Maker XP)

    - by AzDesign
    This is my first day code script in RMXP. I read tutorials, ruby references, etc and I found myself stuck on a weird problem, here is the scenario: I made a custom script to display layered images Create the class, create an instance variable to hold the array, create a simple method to add an element into it, done The draw method (skipped the rest of the code to this part): def draw image = [] index = 0 for i in [email protected] if image.size > 0 index = image.size end image[index] = Sprite.new image[index].bitmap = RPG::Cache.picture(@components[i][0] + '.png') image[index].x = @x + @components[i][1] image[index].y = @y + @components[i][2] image[index].z = @z + @components[i][3] @test =+ 1 end end Create an event that does these script > $layerz = Layerz.new $layerz.configuration[0] = ['root',0,0,1] > $layerz.configuration[1] = ['bark',0,10,2] > $layerz.configuration[2] = ['branch',0,30,3] > $layerz.configuration[3] = ['leaves',0,60,4] $layerz.draw Run, trigger the event and the result : ERROR! Undefined method`[]' for nil:NilClass pointing at this line on draw method : image[index].bitmap = RPG::Cache.picture(@components[i][0] + '.png') THEN, I changed the method like these just for testing: def draw image = [] index = 0 for i in [email protected] if image.size > 0 index = image.size end image[index] = Sprite.new image[index].bitmap = RPG::Cache.picture(@components[0][0] + '.png') image[index].x = @x + @components[0][1] image[index].y = @y + @components[0][2] image[index].z = @z + @components[0][3] @test =+ 1 end I changed the @components[i][0] to @components[0][0] and IT WORKS, but only the root as it not iterates to the next array index Im stuck here, see : > in single level array, @components[0] and @components[i] has no problem > in multi-dimension array, @components[0][0] has no problem BUT > in multi-dimension array, @components[i][0] produce the error as above > mentioned. any suggestion to fix the error ? Or did I wrote something wrong ?

    Read the article

  • Steam freezes at login screen

    - by Snail284069
    I have just installed Steam on Xubuntu, and after it finished installing it went to the login screen, but the screen is frozen, and I cannot press the buttons. When running Steam though the terminal it says: alex@Craptop:~$ steam Running Steam on ubuntu 14.04 32-bit STEAM_RUNTIME is enabled automatically Installing breakpad exception handler for appid(steam)/version(1400690891_client) Installing breakpad exception handler for appid(steam)/version(1400690891_client) Installing breakpad exception handler for appid(steam)/version(1400690891_client) Installing breakpad exception handler for appid(steam)/version(1400690891_client) Gtk-Message: Failed to load module "overlay-scrollbar" Gtk-Message: Failed to load module "unity-gtk-module" Installing breakpad exception handler for appid(steam)/version(1400690891_client) [0522/174755:WARNING:proxy_service.cc(958)] PAC support disabled because there is no system implementation Fontconfig error: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 70: non-double matrix element Fontconfig error: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 70: non-double matrix element Fontconfig warning: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 78: saw unknown, expected number Installing breakpad exception handler for appid(steam)/version(1400690891_client) Installing breakpad exception handler for appid(steam)/version(1400690891_client) [HTTP Remote Control] HTTP server listening on port 35849. Installing breakpad exception handler for appid(steam)/version(1400690891_client) Installing breakpad exception handler for appid(steam)/version(1400690891_client) Process 2764 created /alex-ValveIPCSharedObjects5 Installing breakpad exception handler for appid(steam)/version(1400690891_client) Generating new string page texture 12: 48x256, total string texture memory is 49.15 KB Generating new string page texture 13: 256x256, total string texture memory is 311.30 KB Generating new string page texture 14: 128x256, total string texture memory is 442.37 KB Generating new string page texture 15: 384x256, total string texture memory is 835.58 KB and then the terminal gets stuck too, letting me type into it but not doing anything. I tried reinstalling and restarting the computer, but it still keeps happening.

    Read the article

  • New install of Steam not running on new install of Ubuntu 13.10

    - by inferKNOX
    I tried purging steam, un-installing and reinstalling steam, deleting /home/.steam/share/steam/appcache/, deleting everything in /home/.steam/share/steam/ and nothing helped. I installed Ubuntu, then steam into it directly afterward. I installed steam from Ubuntu Software Centre, launched it, it updated 206MB, then closed. When I tried to launch it again, it momentarily flashes the checking for update dialogue, then closes every time. Then (in an unrelated event) Ubuntu said some system updates are necessary and one of them was Steam launcher. I did the update, tried to launch Steam; same story. Really need help on this, as I did a complete re-isntall of Ubuntu, then Steam again and it did not help at all. Here's the log: user@computer:~$ steam Running Steam on ubuntu 13.10 64-bit STEAM_RUNTIME is enabled automatically Installing breakpad exception handler for appid(steam)/version(1381282832_client) Installing breakpad exception handler for appid(steam)/version(1381282832_client) Installing breakpad exception handler for appid(steam)/version(1381282832_client) unlinked 0 orphaned pipes removing stale semaphore last operated on by process 2297 with name 0eBlobRegistryMutex_313E4D748EE12691A95DDE8913185F7E removing stale semaphore last operated on by process 2297 with name 0eBlobRegistrySignal_313E4D748EE12691A95DDE8913185F7E removing stale semaphore last operated on by process 2297 with name 0emSteamEngineInstance removing stale semaphore last operated on by process 2297 with name 0eSteamEngineLock Gtk-Message: Failed to load module "overlay-scrollbar" Gtk-Message: Failed to load module "unity-gtk-module" Installing breakpad exception handler for appid(steam)/version(1381282832_client) Fontconfig error: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 70: non-double matrix element Fontconfig error: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 70: non-double matrix element Fontconfig warning: "/etc/fonts/conf.d/10-scale-bitmap-fonts.conf", line 78: saw unknown, expected number [1030/115016:WARNING:proxy_service.cc(958)] PAC support disabled because there is no system implementation Installing breakpad exception handler for appid(steam)/version(1381282832_client) Installing breakpad exception handler for appid(steam)/version(1381282832_client) Installing breakpad exception handler for appid(steam)/version(1381282832_client) Installing breakpad exception handler for appid(steam)/version(1381282832_client) Steam: An X Error occurred X Error of failed request: BadValue (integer parameter out of range for operation) Major opcode of failed request: 18 (X_ChangeProperty) Value in failed request: 0x0 Serial number of failed request: 105 xerror_handler: X failed, continuing Uploading dump (out-of-process) [proxy ''] /tmp/dumps/crash_20131030115012_1.dmp /home/user/.local/share/Steam/steam.sh: line 717: 2650 Segmentation fault (core dumped) $STEAM_DEBUGGER "$STEAMROOT/$PLATFORM/$STEAMEXE" "$@" Finished uploading minidump (out-of-process): success = yes response: CrashID=bp-484ddae7-0b1c-4ae4-be84-42a9c2131030 Thanks in advance.

    Read the article

  • Flattening PDF transparency

    - by Jan
    I have a PDF, made with Inkscape, that uses transparent colors. This image shall be used in a LaTeX document. While preserving the transparency is nice for editing, it can be a problem for printing. Printing usually involves PDF to PS conversion. Since Postscript does not support transparency, this requires either flatting, i.e. creating a vector graphic that works without transparency or rastering, i.e. rendering a bitmap image. When a PDF document containing such a figure is printed (or converted to PS) using Evince (or Cairo or Ghostscript), the whole page gets rendered as a bitmap, rendering fonts ugly (different from other pages). (Adobe Acrobat handles such PDFs well.) Unfortunately, converting the PDF figures to EPS (before including them with LaTeX) doesn't help much, because both pdftops and pdf2ps (again, Cairo or Ghostscript) rasterize the image, i.e. render a bitmap (saved as EPS). (This is slightly better, because it doesn't affect the whole page, but I'd still prefer a vector graphics.) How can I flatten transparency with Inkscape or other software on Linux?

    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

  • How to store bitmaps in memory?

    - by Geotarget
    I'm working with general purpose image rendering, and high-performance image processing, and so I need to know how to store bitmaps in-memory. (24bpp/32bpp, compressed/raw, etc) I'm not working with 3D graphics or DirectX / OpenGL rendering and so I don't need to use graphics card compatible bitmap formats. My questions: What is the "usual" or "normal" way to store bitmaps in memory? (in C++ engines/projects?) How to store bitmaps for high-performance algorithms, such that read/write times are the fastest? (fixed array? with/without padding? 24-bpp or 32-bpp?) How to store bitmaps for applications handling a lot of bitmap data, to minimize memory usage? (JPEG? or a faster [de]compression algorithm?) Some possible methods: Use a fixed packed 24-bpp or 32-bpp int[] array and simply access pixels using pointer access, all pixels are allocated in one continuous memory chunk (could be 1-10 MB) Use a form of "sparse" data storage so each line of the bitmap is allocated separately, reusing more memory and requiring smaller contiguous memory segments Store bitmaps in its compressed form (PNG, JPG, GIF, etc) and unpack only when its needed, reducing the amount of memory used. Delete the unpacked data if its not used for 10 secs.

    Read the article

  • Android Game Development problem whith size and speed

    - 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; // if i dont put blockSpeed and put eg 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; } }

    Read the article

  • Recommended formats to store bitmaps in memory?

    - by Geotarget
    I'm working with general purpose image rendering, and high-performance image processing, and so I need to know how to store bitmaps in-memory. (24bpp/32bpp, compressed/raw, etc) I'm not working with 3D graphics or DirectX / OpenGL rendering and so I don't need to use graphics card compatible bitmap formats. My questions: What is the "usual" or "normal" way to store bitmaps in memory? (in C++ engines/projects?) How to store bitmaps for high-performance algorithms, such that read/write times are the fastest? (fixed array? with/without padding? 24-bpp or 32-bpp?) How to store bitmaps for applications handling a lot of bitmap data, to minimize memory usage? (JPEG? or a faster [de]compression algorithm?) Some possible methods: Use a fixed packed 24-bpp or 32-bpp int[] array and simply access pixels using pointer access, all pixels are allocated in one continuous memory chunk (could be 1-10 MB) Use a form of "sparse" data storage so each line of the bitmap is allocated separately, reusing more memory and requiring smaller contiguous memory segments Store bitmaps in its compressed form (PNG, JPG, GIF, etc) and unpack only when its needed, reducing the amount of memory used. Delete the unpacked data if its not used for 10 secs.

    Read the article

  • ArgumentError: Error #2015: Invalid BitmapData.

    - by numerical25
    I am having problems loading a bitmapData. I am getting the following error Engine Init //trace loadimage//trace ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData() Below is my code. it appears it happens after the trace loadimage package com.objects { import flash.display.Sprite; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Point; import flash.geom.Rectangle; import flash.display.Loader; import flash.net.URLRequest; import flash.net.*; import flash.events.*; import flash.display.LoaderInfo; public class gameObject extends Sprite { protected var w:Number; protected var h:Number; protected var image:BitmapData; protected var canvas:Bitmap; protected var px:Number; protected var py:Number; public function gameObject():void { init(); } private function init():void { } public function loadImage(imageDir:String, w:Number, h:Number, px:Number, py:Number):void { this.w = w; this.y = y; this.px = px; this.py = py; trace("loadimage"); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageComplete); loader.load(new URLRequest(imageDir)); } private function imageComplete(e:Event):void { var loader:LoaderInfo = LoaderInfo(e.target); image = Bitmap(loader.content).bitmapData; drawImage(); } private function drawImage():void { var tilePoint:Point = new Point(0,0); var tileRect = new Rectangle(py,px,w,h); trace(loader.content); var canvasData:BitmapData = new BitmapData(w,h); trace("got canvas data"); canvasData.copyPixels(image,tileRect,tilePoint); trace("copied pixels"); canvas = new Bitmap(canvasData); } } } And my call the the method is like so balls = new Array(); balls[0] = new gameObject(); balls[0].loadImage("com/images/ball.gif", 15,15,0,0); When I trace the Loader.content, below is what shows Engine Init loadimage [object Bitmap] ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData()

    Read the article

  • Help with Collision Resolution?

    - by Milo
    I'm trying to learn about physics by trying to make a simplified GTA 2 clone. My only problem is collision resolution. Everything else works great. I have a rigid body class and from there cars and a wheel class: class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private OBB2D predictionRect = new OBB2D(new Vector2D(), 1.0f, 1.0f, 0.0f); private float mass; private Vector2D deltaVec = new Vector2D(); private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); predictionRect.set(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position, getWidth(), getHeight(), angle); rectChanged(); } public void setPredictionLocation(Vector2D position, float angle) { getPredictionRect().set(position, getWidth(), getHeight(), angle); } public void setPredictionCenter(Vector2D center) { getPredictionRect().moveTo(center); } public void setPredictionAngle(float angle) { predictionRect.setAngle(angle); } public Vector2D getPosition() { return getRect().getCenter(); } public OBB2D getPredictionRect() { return predictionRect; } @Override public void update(float timeStep) { doUpdate(false,timeStep); } public void doUpdate(boolean prediction, float timeStep) { //integrate physics //linear Vector2D acceleration = Vector2D.scalarDivide(forces, mass); if(prediction) { Vector2D velocity = Vector2D.add(this.velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep)); setPredictionCenter(c); //forces = new Vector2D(0,0); //clear forces } else { velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); deltaVec.x = v.x - c.x; deltaVec.y = v.y - c.y; deltaVec.normalize(); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; } //angular float angAcc = torque / inertia; if(prediction) { float angularVelocity = this.angularVelocity + angAcc * timeStep; setPredictionAngle(getAngle() + angularVelocity * timeStep); //torque = 0; //clear torque } else { angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } } public void updatePrediction(float timeStep) { doUpdate(true, timeStep); } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity); } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } public Vector2D getDeltaVec() { return deltaVec; } } Vehicle public class Wheel { private Vector2D forwardVec; private Vector2D sideVec; private float wheelTorque; private float wheelSpeed; private float wheelInertia; private float wheelRadius; private Vector2D position = new Vector2D(); public Wheel(Vector2D position, float radius) { this.position = position; setSteeringAngle(0); wheelSpeed = 0; wheelRadius = radius; wheelInertia = (radius * radius) * 1.1f; } public void setSteeringAngle(float newAngle) { Matrix mat = new Matrix(); float []vecArray = new float[4]; //forward Vector vecArray[0] = 0; vecArray[1] = 1; //side Vector vecArray[2] = -1; vecArray[3] = 0; mat.postRotate(newAngle / (float)Math.PI * 180.0f); mat.mapVectors(vecArray); forwardVec = new Vector2D(vecArray[0], vecArray[1]); sideVec = new Vector2D(vecArray[2], vecArray[3]); } public void addTransmissionTorque(float newValue) { wheelTorque += newValue; } public float getWheelSpeed() { return wheelSpeed; } public Vector2D getAnchorPoint() { return position; } public Vector2D calculateForce(Vector2D relativeGroundSpeed, float timeStep, boolean prediction) { //calculate speed of tire patch at ground Vector2D patchSpeed = Vector2D.scalarMultiply(Vector2D.scalarMultiply( Vector2D.negative(forwardVec), wheelSpeed), wheelRadius); //get velocity difference between ground and patch Vector2D velDifference = Vector2D.add(relativeGroundSpeed , patchSpeed); //project ground speed onto side axis Float forwardMag = new Float(0.0f); Vector2D sideVel = velDifference.project(sideVec); Vector2D forwardVel = velDifference.project(forwardVec, forwardMag); //calculate super fake friction forces //calculate response force Vector2D responseForce = Vector2D.scalarMultiply(Vector2D.negative(sideVel), 2.0f); responseForce = Vector2D.subtract(responseForce, forwardVel); float topSpeed = 500.0f; //calculate torque on wheel wheelTorque += forwardMag * wheelRadius; //integrate total torque into wheel wheelSpeed += wheelTorque / wheelInertia * timeStep; //top speed limit (kind of a hack) if(wheelSpeed > topSpeed) { wheelSpeed = topSpeed; } //clear our transmission torque accumulator wheelTorque = 0; //return force acting on body return responseForce; } public void setTransmissionTorque(float newValue) { wheelTorque = newValue; } public float getTransmissionTourque() { return wheelTorque; } public void setWheelSpeed(float speed) { wheelSpeed = speed; } } //our vehicle object public class Vehicle extends RigidBody { private Wheel [] wheels = new Wheel[4]; private boolean throttled = false; public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //front wheels wheels[0] = new Wheel(new Vector2D(halfSize.x, halfSize.y), 0.45f); wheels[1] = new Wheel(new Vector2D(-halfSize.x, halfSize.y), 0.45f); //rear wheels wheels[2] = new Wheel(new Vector2D(halfSize.x, -halfSize.y), 0.75f); wheels[3] = new Wheel(new Vector2D(-halfSize.x, -halfSize.y), 0.75f); super.initialize(halfSize, mass, bitmap); } public void setSteering(float steering) { float steeringLock = 0.13f; //apply steering angle to front wheels wheels[0].setSteeringAngle(steering * steeringLock); wheels[1].setSteeringAngle(steering * steeringLock); } public void setThrottle(float throttle, boolean allWheel) { float torque = 85.0f; throttled = true; //apply transmission torque to back wheels if (allWheel) { wheels[0].addTransmissionTorque(throttle * torque); wheels[1].addTransmissionTorque(throttle * torque); } wheels[2].addTransmissionTorque(throttle * torque); wheels[3].addTransmissionTorque(throttle * torque); } public void setBrakes(float brakes) { float brakeTorque = 15.0f; //apply brake torque opposing wheel vel for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); wheel.addTransmissionTorque(-wheelVel * brakeTorque * brakes); } } public void doUpdate(float timeStep, boolean prediction) { for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); //apply negative force to naturally slow down car if(!throttled && !prediction) wheel.addTransmissionTorque(-wheelVel * 0.11f); Vector2D worldWheelOffset = relativeToWorld(wheel.getAnchorPoint()); Vector2D worldGroundVel = pointVelocity(worldWheelOffset); Vector2D relativeGroundSpeed = worldToRelative(worldGroundVel); Vector2D relativeResponseForce = wheel.calculateForce(relativeGroundSpeed, timeStep,prediction); Vector2D worldResponseForce = relativeToWorld(relativeResponseForce); applyForce(worldResponseForce, worldWheelOffset); } //no throttling yet this frame throttled = false; if(prediction) { super.updatePrediction(timeStep); } else { super.update(timeStep); } } @Override public void update(float timeStep) { doUpdate(timeStep,false); } public void updatePrediction(float timeStep) { doUpdate(timeStep,true); } public void inverseThrottle() { float scalar = 0.2f; for(Wheel wheel : wheels) { wheel.setTransmissionTorque(-wheel.getTransmissionTourque() * scalar); wheel.setWheelSpeed(-wheel.getWheelSpeed() * 0.1f); } } } And my big hack collision resolution: private void update() { camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f), (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f)); //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f); if(input.isPressed(ControlButton.BUTTON_GAS)) { vehicle.setThrottle(1.0f, false); } if(input.isPressed(ControlButton.BUTTON_STEAL_CAR)) { vehicle.setThrottle(-1.0f, false); } if(input.isPressed(ControlButton.BUTTON_BRAKE)) { vehicle.setBrakes(1.0f); } vehicle.setSteering(input.getAnalogStick().getStickValueX()); //vehicle.update(16.6666666f / 1000.0f); boolean colided = false; vehicle.updatePrediction(16.66666f / 1000.0f); List<Entity> buildings = world.queryStaticSolid(vehicle,vehicle.getPredictionRect()); if(buildings.size() > 0) { colided = true; } if(!colided) { vehicle.update(16.66f / 1000.0f); } else { Vector2D delta = vehicle.getDeltaVec(); vehicle.setVelocity(Vector2D.negative(vehicle.getVelocity().multiply(0.2f)). add(delta.multiply(-1.0f))); vehicle.inverseThrottle(); } } Here is OBB public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } }; What I do is when I predict a hit on the car, I force it back. It does not work that well and seems like a bad idea. What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it. Thanks I found this nice ppt. It talks about pulling objects apart and calculating new velocities. How could I calc new velocities in my case? http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CC8QFjAB&url=http%3A%2F%2Fcoitweb.uncc.edu%2F~tbarnes2%2FGameDesignFall05%2FSlides%2FCh4.2-CollDet.ppt&ei=x4ucULy5M6-N0QGRy4D4Cg&usg=AFQjCNG7FVDXWRdLv8_-T5qnFyYld53cTQ&cad=rja

    Read the article

  • .NET OCRing an Image

    - by Kirschstein
    I'm trying to use MODI to OCR a window's program. It works fine for screenshots I grab programmatically using win32 interop like this: public string SaveScreenShotToFile() { RECT rc; GetWindowRect(_hWnd, out rc); int width = rc.right - rc.left; int height = rc.bottom - rc.top; Bitmap bmp = new Bitmap(width, height); Graphics gfxBmp = Graphics.FromImage(bmp); IntPtr hdcBitmap = gfxBmp.GetHdc(); PrintWindow(_hWnd, hdcBitmap, 0); gfxBmp.ReleaseHdc(hdcBitmap); gfxBmp.Dispose(); string fileName = @"c:\temp\screenshots\" + Guid.NewGuid().ToString() + ".bmp"; bmp.Save(fileName); return fileName; } This image is then saved to a file and ran through MODI like this: private string GetTextFromImage(string fileName) { MODI.Document doc = new MODI.DocumentClass(); doc.Create(fileName); doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true); MODI.Image img = (MODI.Image)doc.Images[0]; MODI.Layout layout = img.Layout; StringBuilder sb = new StringBuilder(); for (int i = 0; i < layout.Words.Count; i++) { MODI.Word word = (MODI.Word)layout.Words[i]; sb.Append(word.Text); sb.Append(" "); } if (sb.Length > 1) sb.Length--; return sb.ToString(); } This part works fine, however, I don't want to OCR the entire screenshot, just portions of it. I try cropping the image programmatically like this: private string SaveToCroppedImage(Bitmap original) { Bitmap result = original.Clone(new Rectangle(0, 0, 250, 250), original.PixelFormat); var fileName = "c:\\" + Guid.NewGuid().ToString() + ".bmp"; result.Save(fileName, original.RawFormat); return fileName; } and then OCRing this smaller image, however MODI throws an exception; 'OCR running error', the error code is -959967087. Why can MODI handle the original bitmap but not the smaller version taken from it?

    Read the article

  • How can I fix this touch event / draw loop "deadlock"?

    - by Josh
    Just want to start out by saying this seems like a great site, hope you guys can help! I'm trying to use the structure laid out in LunarLander to create a simple game in which the user can drag some bitmaps around on the screen (the actual game is more complex, but that's not important). I ripped out the irrelevant parts of LanderLander, and set up my own bitmap drawing, something like BoardThread (an inner class of BoardView): run() { while(mRun) { canvas = lockSurfaceHolder... syncronized(mSurfaceHolder) { /* drawStuff using member position fields in BoardView */ } unlockSurfaceHolder } } My drawStuff simply walks through some arrays and throws bitmaps onto the canvas. All that works fine. Then I wanted to start handling touch events so that when the user presses a bitmap, it is selected, when the user unpresses a bitmap, it is deselected, and if a bitmap is selected during a touch move event, the bitmap is dragged. I did this stuff by listening for touch events in the BoardView's parent, BoardActivity, and passing them down into the BoardView. Something like In BoardView handleTouchEvent(MotionEvent e) { synchronized(mSurfaceHolder) { /* Modify shared member fields in BoardView so BoardThread can render the bitmaps */ } } This ALSO works fine. I can drag my tiles around the screen no problem. However, every once in a while, when the app first starts up and I trigger my first touch event, the handleTouchEvent stops executing at the synchronized line (as viewed in DDMS). The drawing loop is active during this time (I can tell because a timer changes onscreen), and it usually takes several seconds or more before a bunch of touch events come through the pipeline and everything is fine again. This doesn't seem like deadlock to me, since the draw loop is constantly going in and out of its syncronized block. Shouldn't this allow the event handling thread to grab a lock on mSurfaceHolder? What's going on here? Anyone have suggestions for improving how I've structured this? Some other info. This "hang" only ever occurs on first touch event after activity start. This includes on orientation change after restoreState has been called. Also, I can remove EVERYTHING within the syncronized block in the event handler, and it will still get hung up at the syncronized call. Thanks!

    Read the article

  • DBConcurrencyException happening on second delete

    - by Malfist
    My code keeps throwing a DBConcurrencyException ("Concurrency violation: the DeleteCommand affected 0 of the expected 1 records.) when I make a second update to the data table. The problem actually happens on a table that is linked to a parent table. The two tables, CashReceipts and CashReceiptsApplyTo are displayed on the same winform, and when I delete two cash receipts the update on cash receipt apply to's table fails with the dbconcurrencyexception (the table is updated everytime the binding source [linked to a binding navigator] changes position). Here is my code: protected override void saveToDatabase() { tblCashReceiptsBindingSource.EndEdit(); tblCashReceiptsTableAdapter.Update(rentalEaseDataSet.tblCashReceipts); //update the datatable foreach (DataGridViewRow viewRow in viewApplications.Rows) { if (viewRow.Cells[colAppID.Index].Value == null || viewRow.Cells[colApplyTo.Index].Value == null) { continue; } else if ((int)viewRow.Cells[colAppID.Index].Value == -1) { insertNewRow(viewRow); } else { updateRow(viewRow); } } try { tblCashReceiptsApplyToTableAdapter.Update(rentalEaseDataSet.tblCashReceiptsApplyTo); //tblCashReceiptsApplyToTableAdapter.Fill(rentalEaseDataSet.tblCashReceiptsApplyTo); ); } catch (Exception e) { Bitmap bitmap = new Bitmap(this.Width, this.Height); this.DrawToBitmap(bitmap, new Rectangle(0, 0, this.Width, this.Height)); saveScreenshot(this.GetType().FullName, e.Message, bitmap); MessageBox.Show("There was an error saving your changes. This means that you should close the form, and re-enter the last Receipt you entered.\n\nPlease report this."); } } The insertNewRow, and updateRow are simple: private void updateRow(DataGridViewRow viewRow) { //be forgiving if ((int)viewRow.Cells[colAppID.Index].Value == -1) { insertNewRow(viewRow); return; } //find row in table, if it's not there, crash and burn RentalEaseDataSet.tblCashReceiptsApplyToRow updateRow = rentalEaseDataSet.tblCashReceiptsApplyTo.Select("ID = " + viewRow.Cells[colAppID.Index].Value.ToString())[0] as RentalEaseDataSet.tblCashReceiptsApplyToRow; updateRow.BeginEdit(); updateRow.CashReceiptsID = (int)viewRow.Cells[colCashReceipt.Index].Value; updateRow.ApplyTo = (int)viewRow.Cells[colApplyTo.Index].Value; updateRow.Paid = CurrencyToDecimal(viewRow.Cells[colPaid.Index].Value); if (viewRow.Cells[colMemo.Index].Value != null) { updateRow.Memo = viewRow.Cells[colMemo.Index].Value.ToString(); } else { updateRow.SetMemoNull(); } updateRow.EndEdit(); } private void insertNewRow(DataGridViewRow viewRow) { //be forgiving if ((int)viewRow.Cells[colAppID.Index].Value != -1) { updateRow(viewRow); return; } RentalEaseDataSet.tblCashReceiptsApplyToRow newRow = rentalEaseDataSet.tblCashReceiptsApplyTo.NewRow() as RentalEaseDataSet.tblCashReceiptsApplyToRow; newRow.CashReceiptsID = (int) viewRow.Cells[colCashReceipt.Index].Value; newRow.ApplyTo = (int) viewRow.Cells[colApplyTo.Index].Value; newRow.Paid = CurrencyToDecimal(viewRow.Cells[colPaid.Index].Value); if (viewRow.Cells[colMemo.Index].Value != null) { newRow.Memo = viewRow.Cells[colMemo.Index].Value.ToString(); } rentalEaseDataSet.tblCashReceiptsApplyTo.Rows.Add(newRow); //update the ID viewRow.Cells[colAppID.Index].Value = newRow.ID; } Any idea why it would throw that error on the second delete?

    Read the article

  • Sprite animation in openGL - Some frames are being skipped

    - by Sid
    Earlier, I was facing problems on implementing sprite animation in openGL ES. Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it. What I need : A sprite animation should stop at the last frame without skipping any frame. What I did : Collision Detection function and working properly. PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case. ------------------------ EDIT----------------------- My sprite sheet. Consider the animation from Left to right and then from top to bottom Here is an image for a better understanding. My spritesheet ... class FragileSquare{ FloatBuffer fVertexBuffer, mTextureBuffer; ByteBuffer mColorBuff; ByteBuffer mIndexBuff; int[] textures = new int[1]; public boolean beingHitFromBall = false; int numberSprites = 20; int columnInt = 4; //number of columns as int float columnFloat = 4.0f; //number of columns as float float rowFloat = 5.0f; int oldIdx; public FragileSquare() { // TODO Auto-generated constructor stub float vertices [] = {-1.0f,1.0f, //byte index 0 1.0f, 1.0f, //byte index 1 //byte index 2 -1.0f, -1.0f, 1.0f,-1.0f}; //byte index 3 float textureCoord[] = { 0.0f,0.0f, 0.25f,0.0f, 0.0f,0.20f, 0.25f,0.20f }; byte indices[] = {0, 1, 2, 1, 2, 3 }; ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float byteBuffer.order(ByteOrder.nativeOrder()); fVertexBuffer = byteBuffer.asFloatBuffer(); fVertexBuffer.put(vertices); fVertexBuffer.position(0); ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4); byteBuffer2.order(ByteOrder.nativeOrder()); mTextureBuffer = byteBuffer2.asFloatBuffer(); mTextureBuffer.put(textureCoord); mTextureBuffer.position(0); } public void draw(GL10 gl){ gl.glFrontFace(GL11.GL_CW); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); if(MyRender.flag2==1){ /** Collision has taken place*/ int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); oldIdx = idx; } gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4 gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5 gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7 gl.glFrontFace(GL11.GL_CCW); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glLoadIdentity(); gl.glMatrixMode(GL10.GL_MODELVIEW); } public void loadFragileTexture(GL10 gl, Context context, int resource) { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource); gl.glGenTextures(1, textures, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); }

    Read the article

  • [Silverlight] How to watermark a WriteableBitmap with a text

    - by Benjamin Roux
    Hello, In my current project, I needed to watermark a WriteableBitmap with a text. As I couldn’t find anything I decided to create a small extension method to do so. public static class WriteableBitmapEx { /// <summary> /// Creates a watermark on the specified image /// </summary> /// <param name="input">The image to create the watermark from</param> /// <param name="watermark">The text to watermark</param> /// <param name="color">The color - default is White</param> /// <param name="fontSize">The font size - default is 50</param> /// <param name="opacity">The opacity - default is 0.25</param> /// <param name="hasDropShadow">Specifies if a drop shadow effect must be added - default is true</param> /// <returns>The watermarked image</returns> public static WriteableBitmap Watermark(this WriteableBitmap input, string watermark, Color color = default(Color), double fontSize = 50, double opacity = 0.25, bool hasDropShadow = true) { var watermarked = GetTextBitmap(watermark, fontSize, color == default(Color) ? Colors.White : color, opacity, hasDropShadow); var width = watermarked.PixelWidth; var height = watermarked.PixelHeight; var result = input.Clone(); var position = new Rect(input.PixelWidth - width - 20 /* right margin */, input.PixelHeight - height, width, height); result.Blit(position, watermarked, new Rect(0, 0, width, height)); return result; } /// <summary> /// Creates a WriteableBitmap from a text /// </summary> /// <param name="text"></param> /// <param name="fontSize"></param> /// <param name="color"></param> /// <param name="opacity"></param> /// <param name="hasDropShadow"></param> /// <returns></returns> private static WriteableBitmap GetTextBitmap(string text, double fontSize, Color color, double opacity, bool hasDropShadow) { TextBlock txt = new TextBlock(); txt.Text = text; txt.FontSize = fontSize; txt.Foreground = new SolidColorBrush(color); txt.Opacity = opacity; if (hasDropShadow) txt.Effect = new DropShadowEffect(); WriteableBitmap bitmap = new WriteableBitmap((int)txt.ActualWidth, (int)txt.ActualHeight); bitmap.Render(txt, null); bitmap.Invalidate(); return bitmap; } } For this code to run, you need the WritableBitmapEx library. As you can see, it’s quite simple. You just need to call the Watermark method and pass it the text you want to add in your image. You can also pass optional parameters like the color, the opacity, the fontsize or if you want a drop shadow effect. I could have specify other parameters like the position or the the font family but you can change the code if you need to. Here’s what it can give Hope this helps.

    Read the article

  • Android - Images from Assets folder in a GridView

    - by Saran
    Hi, I have been working on creating a Grid View of images, with images being present in the Assets folder. http://stackoverflow.com/questions/1933015/opening-an-image-file-inside-the-assets-folder link helped me with using the bitmap to read it. The code am currently having is: public View getView(final int position, View convertView, ViewGroup parent) { try { AssetManager am = mContext.getAssets(); String list[] = am.list(""); int count_files = imagelist.length; for(int i= 0;i<=count_files; i++) { BufferedInputStream buf = new BufferedInputStream(am.open(list[i])); Bitmap bitmap = BitmapFactory.decodeStream(buf); imageView.setImageBitmap(bitmap); buf.close(); } } catch (IOException e) { e.printStackTrace(); } } My application does read the image from the Assets folder, but it is not iterating through the cells in the grid view. All the cells of the grid view have a same image picked from the set of images. Can anyone tell me how to iterate through the cells and still have different images ? I have the above code in an ImageAdapter Class which extends the BaseAdapter class, and in my main class I am linking that with my gridview by: GridView gv =(GridView)findViewById(R.id.gridview); gv.setAdapter(new ImageAdapter(this, assetlist)); Thanks a lot for any help in advance, Saran

    Read the article

  • [SOLVED] BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); } // Do the actual decoding options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • Wpf: Why is WriteableBitmap getting slower?

    - by fritz
    There is a simple MSDN example about WriteableBitmap. It shows how to draw a freehand line with the cursor by just updating one pixel when the mouse is pressed and is moving over a WPF -Image Control. writeableBitmap.Lock(); (...set the writeableBitmap.BackBuffers pixel value...) writeableBitmap.AddDirtyRect(new Int32Rect(column, row, 1, 1)); writeableBitmap.Unlock(); Now I'm trying to understand the following behaviour when moving the mouse pointer very fast: If the image/bitmap size is relatively small e.g. 800:600 pixel, then the last drawn pixel is always "synchronized" with the mouse pointers position, i.e. there is no delay, very fast reaction on mouse movements. But if the bitmap gets larger e.g. 1300:1050 pixel, you can notice a delay, the last drawn pixel always appear a bit delayed behind the moving mouse pointer. So as in both cases only one pixel gets updated with "AddDirtyRect", the reaction speed should be independent from the bitmap size!? But it seems that Writeablebitmap gets slower when it's size gets larger. Or does the whole bitmap somehow get transferred to the graphic device on every writeableBitmap.Unlock(); call , and not only the rectangle area speficied in the AddDirtyRect method? fritz

    Read the article

  • Resizing and saving an image in WinMobile and .NET CF throws OutOfMemoryException

    - by devguy
    I have a WinMobile app which allows the user the snap a photo with the camera, and then use for for various things. The photo can be snapped at 1600x1200, 800x600 or 640x480, but it must always be resized to 400px for the longest size (the other is proportional of course). Here's the code: private void LoadImage(string path) { Image tmpPhoto = new Bitmap(path); // calculate new bitmap size... double width = ... double height = ... // draw new bitmap Image photo = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(photo)) { g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, photo.Width, photo.Height)); int srcX = (int)((double)(tmpPhoto.Width - width) / 2d); int srcY = (int)((double)(tmpPhoto.Height - height) / 2d); g.DrawImage(tmpPhoto, new Rectangle(0, 0, photo.Width, photo.Height), new Rectangle(srcX, srcY, photo.Width, photo.Height), GraphicsUnit.Pixel); } tmpPhoto.Dispose(); // save new image and dispose photo.Save(Path.Combine(config.TempPath, config.TempPhotoFileName), System.Drawing.Imaging.ImageFormat.Jpeg); photo.Dispose(); } Now the problem is that the app breaks in the photo.Save call, with an OutOfMemoryException. And I don't know why, since I dispose the tempPhoto (with the original photo from the camera) as soon as I can, and I also dispose the Graphics obj. Why does this happen? It seems impossible to me that one can't take a photo with the camera and resize/save it without making it crash :( Should I restor t C++ for such a simple thing? Thanks.

    Read the article

  • Is using the .NET Image Conversion enough?

    - by contactmatt
    I've seen a lot of people try to code their own image conversion techniques. It often seems to be very complicated, and ends up using GDI+ function calls, and manipulating bits of the image. This has got me wondering if I am missing something in the simplicity of .NET's image conversion call when saving an image. Here's the code I have: Bitmap tempBmp = new Bitmap("c:\temp\img.jpg"); Bitmap bmp = new Bitmap(tempBmp, 800, 600); bmp.Save(c:\temp\img.bmp, //extension depends on format ImageFormat.Bmp) //These are all the ImageFormats I allow conversion to within the program. Ignore the syntax for a second ;) ImageFormat.Gif) //or ImageFormat.Jpeg) //or ImageFormat.Png) //or ImageFormat.Tiff) //or ImageFormat.Wmf) //or ImageFormat.Bmp)//or ); This is all I'm doing in my image conversion. Just setting the location of where the image should be saved, and passing it an ImageFormat type. I've tested it the best I can, but I'm wondering if I am missing anything in this simple format conversion, or if this is sufficient?

    Read the article

  • Per-pixel per-component alpha blending in Windows

    - by Crend King
    I have a 24-bit bitmaps with R, G, B color channels and a 24-bit bitmap with R, G, B alpha channels. I want to alpha blend the first bitmap to a HDC in GDI or RenderTarget in Direct2D with the alpha channels respectively. For example, suppose for one pixel, the bitmap color is (192, 192, 192), the HDC color is (0, 255, 255) and the alpha channels are (30, 40, 50). The final HDC color should be (22, 245, 242). I know I can BitBlt the HDC to a memory HDC first, do alpha blending by manually calculating the color of each pixel and finally BitBlt back. I just want to avoid the additional blitting and leave APIs do their job (faster since they are in kernel space). The first idea comes to my mind is to split the source bitmap into 3 red-only, green-only and blue-only 8-bit bitmaps, do normal alpha blending, then composite the 3 output bitmaps into the HDC. But I don't find a way to do the splitting and composition natively in Windows (would Direct2D layer help?). Also, the splitting and compositing may require many additional copying. The performance overhead would be too high. Or maybe do the alpha blending in 3 passes. Each pass apply the blending for one channel, while maintaining the other 2 unchanged. Thanks for any comment. EDIT: I found this question, and the answer should be good reference to this problem. However, besides AC_SRC_OVER, there is no other blending operation supported. Why don't Microsoft improve their API?

    Read the article

  • WatiN NativeElement.GetElementBounds() - What is the unit of measurement?

    - by Brian Schroer
    When I'm testing with WatiN, I like to save screenshots. Sometimes I don't really need a picture of the whole browser window though - I just want a picture of the element that I'm testing. My attempt to save a picture of an element with the code below resulted in a picture of a block box, because elementBounds.Top points to a pixel position way past the bottom of the screen. The elementBounds.Width and .Height values also appear to be about half what they should be. Is this a WatiN bug, or are these properties in a different unit of measure that I have to convert to pixels somehow? public static void SaveElementScreenshot (WatiN.Core.IE ie, WatiN.Core.Element element, string screenshotPath) { ScrollIntoView(ie, element); ie.BringToFront(); var ieClass = (InternetExplorerClass) ie.InternetExplorer; Rectangle elementBounds = element.NativeElement.GetElementBounds(); int left = ieClass.Left + elementBounds.Left; int top = ieClass.Top + elementBounds.Top; int width = elementBounds.Width; int height = elementBounds.Height; using (var bitmap = new Bitmap(width, height)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen (new Point(left, top), Point.Empty, new Size(width, height)); } bitmap.Save(screenshotPath, ImageFormat.Jpeg); } }

    Read the article

  • C# .NET : Is using the .NET Image Conversion enough?

    - by contactmatt
    I've seen a lot of people try to code their own image conversion techniques. It often seems to be very complicated, and ends up using GDI+ funciton calls, and manipulating bits of the image. This has got me wondering if I am missing something in the simplicity of .NET's image conversion call when saving an image. Here's the code I have Bitmap tempBmp = new Bitmap("c:\temp\img.jpg"); Bitmap bmp = new Bitmap(tempBmp, 800, 600); bmp.Save(c:\temp\img.bmp, //extension depends on format ImageFormat.Bmp) //These are all the ImageFormats I allow conversion to within the program. Ignore the syntax for a second ;) ImageFormat.Gif) //or ImageFormat.Jpeg) //or ImageFormat.Png) //or ImageFormat.Tiff) //or ImageFormat.Wmf) //or ImageFormat.Bmp)//or ); This is all I'm doing in my image conversion. Just setting the location of where the image should be saved, and passing it an ImageFormat type. I've tested it the best I can, but I'm wondering if I am missing anything in this simple format conversion, or if this is suffice?

    Read the article

  • BlackBerry:Reduce space between 2 buttons in HorizontalFieldManager

    - by user469999
    hi In blackberry i have created a horizontal field managar and added some buttons of small size to it to display toolbar at the bottom of the screen.But my problem is there is too much space between the 2 buttons.I have to reduce this space between 2 buttons so that i can manage to place atleast 6 buttons at the bottom of the screen.I am using the BFmsg.setMargin(305,0,0,40) statement. can anyone please help me on this. Following is my code : BFcontacts = new ButtonField("Cnt") { protected void paint(Graphics graphics) { //Bitmap contactsbitmap = Bitmap.getBitmapResource("contacts.jpg"); //graphics.drawBitmap(0, 0, contactsbitmap.getWidth(), contactsbitmap.getHeight(), contactsbitmap, 0, 0); graphics.setColor(Color.WHITE); graphics.drawText("Cnt",0,0); } }; BFcontacts.setMargin(305,0,0,10);//vertical pos,0,0,horizontal pos HFM.add(BFcontacts); BFmsg = new ButtonField("Msgs") { protected void paint(Graphics graphics) { //Bitmap msgsbitmap = Bitmap.getBitmapResource("messages.jpg"); //graphics.drawBitmap(0, 0, msgsbitmap.getWidth(), msgsbitmap.getHeight(), msgsbitmap, 0, 0); graphics.setColor(Color.WHITE); graphics.drawText("Msgs",0,0); } }; BFmsg.setMargin(305,0,0,40);//vertical pos,0,0,horizontal pos : original HFM.add(BFmsg); add(HFM) Thanks in advance

    Read the article

  • Put together tiles in android sdk and use as background

    - by Jon
    In a feeble attempt to learn some Android development am I stuck at graphics. My aim here is pretty simple: Take n small images and build a random image, larger than the screen with possibility to scroll around. Have an animated object move around on it I have looked at the SDK examples, Lunar Lander especially but there are a few things I utterly fail to wrap my head around. I've got a birds view plan (which in my head seems reasonably sane): How do I merge the tiles into one large image? The background is static so I figure I should do like this: Make a 2d array with refs to the tiles Make a large Drawable and draw the tiles on it At init draw this big image as the background At each onDraw redraw the background of the previous spot of the moving object, and the moving object at its new location The problem is the hands on things. I load the small images with "Bitmap img1 = BitmapFactory.decodeResource (res, R.drawable.img1)", but then what? Should I make a canvas and draw the images on it with "canvas.drawBitmap (img1, x, y, null);"? If so how to get a Drawable/Bitmap from that? I'm totally lost here, and would really appreciate some hands on help (I would of course be grateful for general hints as well, but I'm primarily trying to understand the Graphics objects). To make you, dear reader, see my level of confusion will I add my last desperate try: Drawable drawable; Canvas canvas = new Canvas (); Bitmap img1 = BitmapFactory.decodeResource (res, R.drawable.img1); // 50 x 100 px image Bitmap img2 = BitmapFactory.decodeResource (res, R.drawable.img2); // 50 x 100 px image canvas.drawBitmap (img1, 0, 0, null); canvas.drawBitmap (img2, 50, 0, null); drawable.draw (canvas); // obviously wrong as draw == null this.setBackground (drawable); Thanks in advance

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >