is it possible in Unity to slice image from the middle? - image

I get an image from the backend which I want to put in a puzzle shuffle game, however right now it is cropping from left to almost middle of the image , I would like to crop the center of the image, I was trying to use another Sprite which I cropped to the middle then use it in the ImageSlicer however I am getting same results.
Here are the images :
Main Image , Cropped Image as temp , Sliced Image as imagesSlices
am I doing the right thing and maybe I'm messing something in the code or this isn't how I should crop and slice ?
Sprite temp = Sprite.Create(currentImage, new Rect(currentImage.width * 0.25f, 0, currentImage.width * 0.75f, currentImage.height),new Vector2(0.5f, 0.5f), 100.0f);
Texture2D[,] imageSlices = ImageSlicer.GetSlices(temp.texture, blocksPerLine);

So the texture was staying the same and I was trying to get a new sprite not a new texture but I need a new cropped texture to work with which is why the sliced images were taken from old texture.

Related

Is it possible to save a generated image in Codename One?

My question is related to this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
#Override
protected void beforeMain(Form f) {
Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
Image watermark = fetchResourceFile().getImage("Watermark.png");
f.setLayout(new LayeredLayout());
final Label drawing = new Label();
f.addComponent(drawing);
// Image mutable dans laquelle on va dessiner (fond blanc)
Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
drawing.getUnselectedStyle().setBgImage(mutableImage);
drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
// Paint all the stuff
paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());
// Save the collage
Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
f.revalidate();
f.setVisible(true);
drawing.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
err.printStackTrace();
}
}
public void paints(Graphics g, Image background, Image watermark, int width, int height) {
g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);
// Upper left corner
g.fillRect(0, 0, 10, 10);
// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);
g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld",
(int) (848 ),
(int) (610)
);
}
This is the saved screenshot I get if I use the Iphone6 skin (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the graphics on which I paint in the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,
You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.

Mapping image into cylinder or sphere shape?

So lets say I have black & white image that is read with imread() command and saved into matrix A.
I want to output/graph this matrix A image in a cylinder shape. I know how to draw a cylinder in MATLAB, but I do not have a clue what I should do if I want to put image on a cylinder or draw image in cylinder shape. Any help will be appreciated. Thank you.
I found this site from googling.
http://www.flashandmath.com/advanced/rolls/cylin.html
This is exactly what I want to do, but I need to do this in MATLAB.
The technique is called texture mapping. This is a code example from surface function (R2011b):
load clown
surface(peaks,flipud(X),...
'FaceColor','texturemap',...
'EdgeColor','none',...
'CDataMapping','direct')
colormap(map)
view(-35,45)
This example loads RGB image from "peppers.png" and maps it onto cylinder:
imgRGB = imread('peppers.png');
[imgInd,map] = rgb2ind(imgRGB,256);
[imgIndRows,imgIndCols] = size(imgInd);
[X,Y,Z] = cylinder(imgIndRows,imgIndCols);
surface(X,Y,Z,flipud(imgInd),...
'FaceColor','texturemap',...
'EdgeColor','none',...
'CDataMapping','direct')
colormap(map)
view(-35,45)
Things are even simpler with the warp function (comes with Image Processing toolbox) as natan suggested:
imgRGB = imread('peppers.png');
[imgRows,imgCols,imgPlanes] = size(imgRGB);
[X,Y,Z] = cylinder(imgRows,imgCols);
warp(X,Y,Z,imgRGB);

Drawing UI elements directly to the WebGL area with Three.js

In Three.js, is it possible to draw directly to the WebGL area (for a heads-up display or UI elements, for example) the way you could with a regular HTML5 canvas element?
If so, how can you get the context and what drawing commands are available?
If not, is there another way to accomplish this, through other Three.js or WebGL-specific drawing commands that would cooperate with Three.js?
My backup plan is to use HTML divs as overlays, but I think there should be a better solution.
Thanks!
You can't draw directly to the WebGL canvas in the same way you do with with regular canvas. However, there are other methods, e.g.
Draw to a hidden 2D canvas as usual and transfer that to WebGL by using it as a texture to a quad
Draw images using texture mapped quads (e.g. frames of your health box)
Draw paths (and shapes) by putting their vertices to a VBO and draw that with the appropriate polygon type
Draw text by using a bitmap font (basically textured quads) or real geometry (three.js has examples and helpers for this)
Using these usually means setting up a an orthographic camera.
However, all this is quite a bit of work and e.g. drawing text with real geometry can be expensive. If you can make do with HTML divs with CSS styling, you should use them as it's very quick to set up. Also, drawing over the WebGL canvas, perhaps using transparency, should be a strong hint to the browser to GPU accelerate its div drawing if it doesn't already accelerate everything.
Also remember that you can achieve quite much with CSS3, e.g. rounded corners, alpha transparency, even 3d perspective transformations as demonstrated by Anton's link in the question's comment.
I had exactly the same issue. I was trying to create a HUD (Head-up display) without DOM and I ended up creating this solution:
I created a separate scene with orthographic camera.
I created a canvas element and used 2D drawing primitives to render my graphics.
Then I created an plane fitting the whole screen and used 2D canvas element as a texture.
I rendered that secondary scene on top of the original scene
That's how the HUD code looks like:
// We will use 2D canvas element to render our HUD.
var hudCanvas = document.createElement('canvas');
// Again, set dimensions to fit the screen.
hudCanvas.width = width;
hudCanvas.height = height;
// Get 2D context and draw something supercool.
var hudBitmap = hudCanvas.getContext('2d');
hudBitmap.font = "Normal 40px Arial";
hudBitmap.textAlign = 'center';
hudBitmap.fillStyle = "rgba(245,245,245,0.75)";
hudBitmap.fillText('Initializing...', width / 2, height / 2);
// Create the camera and set the viewport to match the screen dimensions.
var cameraHUD = new THREE.OrthographicCamera(-width/2, width/2, height/2, -height/2, 0, 30 );
// Create also a custom scene for HUD.
sceneHUD = new THREE.Scene();
// Create texture from rendered graphics.
var hudTexture = new THREE.Texture(hudCanvas)
hudTexture.needsUpdate = true;
// Create HUD material.
var material = new THREE.MeshBasicMaterial( {map: hudTexture} );
material.transparent = true;
// Create plane to render the HUD. This plane fill the whole screen.
var planeGeometry = new THREE.PlaneGeometry( width, height );
var plane = new THREE.Mesh( planeGeometry, material );
sceneHUD.add( plane );
And that's what I added to my render loop:
// Render HUD on top of the scene.
renderer.render(sceneHUD, cameraHUD);
You can play with the full source code here:
http://codepen.io/jaamo/pen/MaOGZV
And read more about the implementation on my blog:
http://www.evermade.fi/pure-three-js-hud/

can't get the image to rotate in center in Qt

i am trying to rotate a 89x89 image inside the QLabel Widge.
#include "header.h"
disc::disc(QWidget *Parent) : QWidget(Parent)
{
orig_pixmap = new QPixmap();
rotate = new QLabel(this);
showDegrees = new QLabel(this);
orig_pixmap->load("pic.png");
degrees = 0;
rotate->resize(89,89);
rotate->move(100,10);
rotate->setStyleSheet("QLabel{background-color:red;}");
showDegrees->resize(100,100);
showDegrees->move(400,0);
}
void disc::rotate_disc()
{
QString string;
degrees++;
if(degrees == 360) degrees = 0;
QTransform rotate_disc;
rotate_disc.translate( (orig_pixmap->width()-rotate->width())/2 , (orig_pixmap->width()-rotate->height())/2);
rotate_disc.rotate(degrees,Qt::ZAxis);
QPixmap pixmap;
//pixmap = orig_disc->scaled(89,89,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
pixmap = orig_pixmap->transformed(rotate_disc,Qt::SmoothTransformation);
rotate->setPixmap(pixmap);
string.append("Degrees: " + QString::number(degrees) + "*");
showDegrees->setText(string);
}
Even though it rotates. The image's half gets rolled outside the QLabel and hence that side is not visible.How can i make it center rotate at origin(0,0) of the image center.
Here is the file
http://www65.zippyshare.com/v/85775455/file.html
if you look at it you can see that image is like bouncing to the left.how can i make it rotate inside the black area.
i setup a signal timeout at every 10ms to the rotate_disc() function. I am using this to learn Qt indepth.
Thank You!
I've done it like this...
//Move windows's coordinate system to center.
QTransform transform_centerOfWindow( 1, 0, 0, 1, width()/2, height()/2 );
//Rotate coordinate system.
transform_centerOfWindow.rotate( m_LoadingDisk_degrees );
//Draw image with offset to center of image.
QPainter painter( this );
//Transform coordinate system.
painter.setTransform( transform_centerOfWindow );
//Load image.
//Notice: As coordinate system is set at center of window, we have to center the image also... so the minus offset to come to center of image.
painter.drawPixmap( -loadingDisk.width()/2, -loadingDisk.height()/2, loadingDisk );
I think all you're really missing is the initial translation to do the rotation around the centre of the pixmap.
Move it to the origin, rotate, then move it back. And remember, transformations are applied in reverse order from how you'd expect, given how you specify them in the code.
QTransform rotate_disc;
rotate_disc.translate(orig_pixmap->width()/2.0 , orig_pixmap->height()/2.0);
rotate_disc.rotate(degrees);
rotate_disc.translate(-orig_pixmap->width()/2.0 , -orig_pixmap->height()/2.0);
If you are making a loading indicator, animated gif would be much easier. See GIF animation in Qt

HTML5 canvas - Rescale images on load?

Ok, so I'm doing an html5 canvas game, and I need to draw resized images all the time (it's all pixel-art). Unfortunately, doing the resizing on drawImage makes current browsers quite sluggish, so I'm trying to do the resizing on load, and then just draw the pre-resized image.
I've tried to draw the resized images to a hidden context and then do a ctx.getImageData, but then I'm stuck with a byte array and there's no way to convert to an image. I can do a putImageData to push it to the final context, but that's slow and I apparently lose the alpha channel.
Another option could be to pre-scale things in the server, but I'd like to avoid that if at all possible.
Any ideas?
There is a method on the canvas object (not the context) called toDataURL(string mimeType), this will convert the canvas contents to a base64-encoded binary string of an image. You can use this as the src attribute of any image element.
ctx.drawImage(originalImage, 0, 0, originalImage.width, originalImage.height, 0, 0, 200, 200);
var scaledImage = new Image();
scaledImage.onload = ...;
scaledImage.src = canvas.toDataURL("image/png");
Now you can draw your scaled image normaly.

Resources