Sprite::createWithTexture with Rect not working as expected - c++

I'm trying to build a sprite from an image. Using Image and Texture2D class and then later creating a sprite from the texture2D.
The image I am loading is 512x512 and I expected both versions of the createWithTexture to behave the same but they don't. Here the code:
Image* image = new Image();
image->initWithImageFile(fileName);
Texture2D* texture = new Texture2D();
texture->initWithImage(image);
//If used this way everything works as expected
Sprite* spr= Sprite::createWithTexture(texture);
//If used with a Rect weird result occurrs.
Sprite* spr= Sprite::createWithTexture(texture,Rect(0,0,512,512));
spr->setAnchorPoint(Vec2(0,0));
spr->setPosition(Vec2(0,0));
spr->setScale(1.0f,1.0f);
this->addChild(spr);
Here the result of the first one using a Rect:
And here the Second version without a Rect:
Do anybody know what is happening? I need to use the method that uses the rect because I will be creating a bunch of sprites from this image in the future.
Edit1: After debugging both versions of the sprite. I have noticed that the one created without the Rect shows a rect of 0,0,240,240. Instead of 0,0,512,512 as I provided. Why 240?
Thanks in advance.

I managed to figure out what was happening. Cocos2D-x uses director->setContentScaleFactor and glview->setDesignResolutionSize as a way to make things easier for multi resolution/device games. When you build the Rect to get a part (or full) texture you must have into account the CC_CONTENT_SCALE_FACTOR() macro, in order to get correct target coordinates.
This can be checked at this link: http://www.cocos2d-x.org/wiki/Multi_resolution_support
Cheers.

If your vecSize is bigger than the image's size, the image will be out of shape.
So if you don't know the image's real size, don't set it.

Related

How to use stock-objects with GDI+

I was using the following pattern to record an enhanced meta-file for a later playback:
POINT pts[] = {
//.....
};
::SelectObject(hEnhDC, ::GetStockObject(LTGRAY_BRUSH));
::Polygon(hEnhDC, pts, _countof(pts));
Now I'm forced to use GDI+ to provide anti-aliasing, so I'm trying to convert that code sample:
Gdiplus::Point pts[] = {
//...
};
Gdiplus::Graphics grx(hEnhDC);
Gdiplus::Pen pen(Gdiplus::Color(255, GetRValue(clrPen), GetGValue(clrPen), GetBValue(clrPen)), PEN_THICKNESS);
grx.FillPolygon(&brush, pts, _countof(pts));
grx.DrawPolygon(&pen, pts, _countof(pts));
The issue is how do I convert a stock-object HBRUSH from ::GetStockObject(LTGRAY_BRUSH) to GDI+ Brush object?
EDIT: Guys, thank you for all your suggestions. And I apologize for not providing more details. This question is not about getting the RGB color triplet from the stock brush. I can do all that with the GetSysColor function, or with the LOGBRUSH like you showed below.
The trick lies in the first sentence above. I am recording an enhanced metafile that may be played on a separate computer, so I cannot hard-code colors into it.
Let me explain. Say, the first GDI example (let's simplify it down to a triangle with a gray fill):
POINT pts[] = {
{100, 100,},
{100, 120,},
{120, 100,},
};
::SelectObject(hEnhDC, ::GetStockObject(LTGRAY_BRUSH));
::Polygon(hEnhDC, pts, _countof(pts));
If I then call GetEnhMetaFileBits on that meta-file, I'll get the following data:
So as you see the EMR_SELECTOBJECT object in that recorded meta-file specifies the LTGRAY_BRUSH = 0x80000001, which will be properly substituted for the color when that meta-file is played on the target system.
And that's what I'm trying to achieve here with GDI+. For some reason it only seems to support hard-coded color triplets in its Brush class. That's why I asked.
Otherwise, one solution is to parse the enhanced meta-file's raw data. (For GDI+ it is a much more complex structure though, that also involves parsing EMR_GDICOMMENT objects.) And then substitute the needed color on the target system before the GDI+ meta-file is played. But it involves writing a lot of code, which I was trying to avoid at this stage ...
I’m afraid you can’t easily convert.
A simple workaround is create GDI+ solid brush with the same color.
See this spec for color values of GDI stock objects, that particular brush has color #C0C0C0

High-DPI scaling of QQuickItem-derived class

I use QtQuickControls 2 together with QQuickItem-derived class in my app. After I set AA_EnableHighDpiScaling attribute and all QQuickControls 2 components look correctly on my smartphone but object of my custom class is scaled incorrectly. Here is the app without HighDpi scaling with minimum zoom(the way it is meant to work):
And here is the one with scaling with minimum zoom:
It seems that on the second screen the object is scaled too much and I can see square pixels of all textures that I draw with QPixmap or QImage. However, the images that I load from external memory and nodes like QSGGeometryNode look correct. Can I switch off scaling for just one particular QQuickItem? If no, what should I set to render it correctly?
Also, when I try to set opacity on QQuickItem with a lot of QSGOpacityNodes in scene graph node tree I get segmentation fault. What can cause this?
So I solved this problem by dividing the size of QSGTexture by QQuickWindow::effectiveDevicePixelRatio() and also multiplying the size of the image from which texture is created by this ratio.
If you are drawing the text using on QImage you should also multiply your font's size by this ratio. The same thing should be done with geometrical shapes and QPixmap::scaled().

How to rotate an image around its centre in QT QWidgets C++?

I am trying to rotate am image around its origin(center) in QT using QWidgts in C++. I experimented a lot of things here, but no matter what I do, the image keeps rotating around some arbitrary position I have no clue of. Kindly, help me out here. I am new to QT.
void gaugeWithRedZoneImage::rotate()
{
QPixmap pixmap(*gaugeMainScreen->pixmap());
QMatrix rm;
rm.translate(0, 0);
rm.rotate(-360);
pixmap = pixmap.transformed(rm);
gaugeMainScreen->setPixmap(pixmap);
/*QTransform rotate_disc;
rotate_disc.translate(pixmap.width()/2.0 , pixmap.height()/2.0);
rotate_disc.rotate(-60);
rotate_disc.translate(-(pixmap.width()/2.0) , -(pixmap.height()/2.0));
pixmap = pixmap.transformed(rotate_disc);
gaugeMainScreen->setPixmap(pixmap);*/
}
Form the documentation of QPixmap::transformed():
The transformation transform is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed points of the original pixmap.
This means that the method ensures no clipping takes place by appending the canvas. No matter what your rotation center was, the automatic extension of canvas will almost always result in a perceived shift.
Image examples might help to further diagnose the problem.
As ypnos said, your problem isn't the rotation center. When you rotate your image, its width and height will most likely change and no longer fit your container (gaugeMainScreen) dimensions.
You have some possibilities to overcome this problem. One of them is to set your container to scale its contents (you can use the method setScaledContents()). In this case, you have to keep the original image around and use it whenever you apply a rotation, otherwise your image will appear increasingly smaller.

changing textureRect of a CCSprite created by CCRenderTexture

I have a CCSprite which gradually needs to be exhausted linearly from one end, lets say from left to right.For this purpose ,I am trying to change the textureRect property of the sprite so that the part that got exhausted from one end is 'outside' the displaying frame of the sprite.
I did this sort of thing before with a sprite that gets loaded from a spritesheet.And it worked perfectly.But I created this CCSprite using CCRenderTexture and by changing the textureRect property,the entire sprite gets disappeared.
The first image is the original CCSprite which I get from CCRenderTexture.The second image shows what I want to achieve.The black dotted rectangular portion of the Sprite needs to be omitted out.Only the blue dotted portion of the sprite needs to be displayed.Essentially,this blue dotted rectangle is my textureRect.
Is there any way how I could make my sprite reduce from one end.
Also is there any difference between a sprite created normally,and one created using CCRenderTexture.
I have done similar thing like this before using some low-level hack.
There is a work around solution if you use CCProgressTimer, that's very easy and I think it should be enough for your examples.
But you said in comment that you have some special requirements like "exhaust it from both the ends at once" then some low-level hack is needed. My solution from my last object is:
1) Get the texture image's raw data. In cocos2d you can use CCRenderTexture and in cocos2d-x you can use CCImage.
2) CCRenderTexture has a method of - (BOOL) saveToFile: (NSString *) name
format: (tCCImageFormat) format
. You can read its source code then try to save it into an 2D array instead like byte raw[1024][768]. Each element in this array represents one pixel on your picture(the type may not be byte, I'm not sure, nearly forget the details). The format MUST BE PNG since transparency will be needed.
3) Modify raw data directly, set pixel's transparency to 0x0 which you want it to disappear.
4) Re-initialize a CCRenderTexture using picture data you modified.
I can't provide the code directly since is a trade secret and core part of one of my projects. But I can share you my solution. You also need some knowledge about how PNG file works. Read:
https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
Turns out I was making a silly mistake.While supplying values to the textureRect(CGRect),I was actually setting the textureRect.origin.y to the height of the texture which made my textureRect go beyond(above) the texture area.This explains why they were disappearing.

How to move background in cocos 2d

Hi i want to develop game like 'Doodle jump'.But i have some problem with the following features-
1.How to move background scene/image.
2.How to detect collision between object.Is it needed a physics engine like box2d or i should just use manual collision.
3.what should be the size of the background image.
4.In fact i have no idea how does background move .So i need a explanation from someone.
Background Movement
A) You could create a TMX Tilemap and then make a very high Tiled-Map.
B) You could create one texture and then cycle the texture coords instead of really moving it.
Detect it manually. Best is detect it via "Point in Boundingbox" or "Rect in Rect".
For more detail visit my blog entry for collision detection with cocos2d : http://www.anima-entertainment.de/?p=262
Size of an Image
Keep in Mind that textures are always at power of 2 in the memory. If you want to create one Background-Image at retina highresolution (960x640 Pixel) in the memory will be a texture of 1024x1024. If possible use smaller Background-Images and stretch them. (like 512x512). But I really would recommend for big scrolling images the TMX Support.
CCTMXTiledMap * tmxNode = [CCTMXTiledMap tiledMapWithGMXFile:#"Level.tmx"];
// lets say you want to move it 50 pixels down in 1 second :
[tmxNode runAction:[CCMoveBy actionWithDuration:1.0 position:ccp(0,-50)];
To create a tilemap : http://www.mapeditor.org/
In the folder of cocos2d, you could get many demos of tilemap.
TileMapTest.h
TileMapTest.m
refer this tutorial this will helpful for you.
http://www.raywenderlich.com/2343/how-to-drag-and-drop-sprites-with-cocos2d
this is used screen movement with pan recognizer