cocos2d box2d scale sprite -> removechild (how?) - sprite

I am little slow in English, please do understand.
Here is my source code:
- (void)createBall:(CGPoint)touchedAt{
CGSize winSize = [CCDirector sharedDirector].winSize;
ball2 = [CCSprite spriteWithFile:#"Ball.png" rect:CGRectMake(0, 0, 54, 54)];
ball2.position = ccp(touchedAt.x,touchedAt.y);
[self addChild:ball2];
b2BodyDef ballBodyDef2;
ballBodyDef2.type = b2_dynamicBody;
ballBodyDef2.position.Set(touchedAt.x/PTM_RATIO, touchedAt.y/PTM_RATIO);
ballBodyDef2.userData = ball2;
b2Body *body2 = _world->CreateBody(&ballBodyDef2);
b2CircleShape circle;
circle.m_radius = 89.0/PTM_RATIO;//(arc4random()*26.0)/PTM_RATIO;
b2FixtureDef ballShapeDef2;
ballShapeDef2.shape = &circle;
ballShapeDef2.density = 1.0f;
ballShapeDef2.friction = 0.2f;
ballShapeDef2.restitution = 0.8f;
body2->CreateFixture(&ballShapeDef2);
}
-(void)createBall2
{
CGSize winSize = [CCDirector sharedDirector].winSize;
globalSprite = [CCSprite spriteWithFile:#"Ball.png"];
globalSprite.position = ccp(winSize.width/2 + globalSprite.contentSize.width, winSize.height/2);
[self addChild:globalSprite];
b2BodyDef ballBodyDef3;
ballBodyDef3.type = b2_dynamicBody;
ballBodyDef3.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
ballBodyDef3.userData = globalSprite ;
b2Body *body3 = _world->CreateBody(&ballBodyDef3);
b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;//(arc4random()*26.0)/PTM_RATIO;
b2FixtureDef ballShapeDef3;
ballShapeDef3.shape = &circle;
ballShapeDef3.density = 1.0f;
ballShapeDef3.friction = 0.2f;
ballShapeDef3.restitution = 0.8f;
body3->CreateFixture(&ballShapeDef3);
}
// initialize your instance here
-(id) init
{
if( (self=[super init])) {
// enable touch
// enable accelerometer
CGSize winSize = [CCDirector sharedDirector].winSize;
self.isAccelerometerEnabled = YES;
self.isTouchEnabled = YES;
// Create sprite and add it to the layer
// Create a world
b2Vec2 gravity = b2Vec2(0.0f, 0.0f);
bool doSleep = true;
_world = new b2World(gravity, doSleep);
// Create edges around the entire screen
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body *groundBody = _world->CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
b2FixtureDef boxShapeDef;
boxShapeDef.shape = &groundBox;
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(0, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
// Create ball body and shape
[self schedule:#selector(tick:)];
//[self schedule:#selector(gameLogic:) interval:1.0];
[self createBall2];
}
return self;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// Choose one of the touches to work with
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
[self createBall:location];
}
- (void)tick:(ccTime) dt {
_world->Step(dt, 10, 10);
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *ballData = (CCSprite *)b->GetUserData();
ballData.position = ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO);
ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
I want to
touch -> sprite create(circle) -> sprite scale -> sprite remove
but
- (void)tick:(ccTime) dt <---------- this is simulator turn off!
I want to way

Try this :
world->DestroyBody(sprite);

Related

Metal blending alpha under 0.5

When I try to blend with a color with an alpha of 0.5 or below, metal seemingly discards the color like it has an alpha of 0. When I set the alpha to 0.51, I can see it fine. When I set it to 0.5, it's invisible. Here is a simple implementation of the issue:
#implementation Renderer
{
id <MTLDevice> _device;
id <MTLCommandQueue> _commandQueue;
id<MTLLibrary> defaultLibrary;
id <MTLBuffer> _vertexBuffer;
id <MTLBuffer> _indexBuffer;
id <MTLRenderPipelineState> _pipelineState;
}
-(nonnull instancetype)initWithMetalKitView:(nonnull MTKView *)view;
{
self = [super init];
if(self)
{
_device = view.device;
view.colorPixelFormat = MTLPixelFormatBGRA8Unorm_sRGB;
_commandQueue = [_device newCommandQueue];
[self _createRenderObject];
}
return self;
}
-(void)_createRenderObject
{
Vertex verts[4] = {
simd_make_float2(-0.5f, -0.5f),
simd_make_float2(0.5f,-0.5f),
simd_make_float2(0.5f,0.5f)
};
uint16_t indices[3] = {0,1,2};
_vertexBuffer = [_device newBufferWithBytes:&verts length:sizeof(verts) options:MTLResourceStorageModeShared];
_indexBuffer = [_device newBufferWithBytes:&indices length:sizeof(indices) options:MTLResourceStorageModeShared];
// Create Pipeline State
defaultLibrary = [_device newDefaultLibrary];
MTLRenderPipelineDescriptor *pd = [[MTLRenderPipelineDescriptor alloc] init];
pd.vertexFunction = [defaultLibrary newFunctionWithName: #"VertShader"];
pd.fragmentFunction = [defaultLibrary newFunctionWithName: #"FragShader"];
pd.alphaToCoverageEnabled = YES;
MTLRenderPipelineColorAttachmentDescriptor *cad = pd.colorAttachments[0];
cad.pixelFormat = MTLPixelFormatBGRA8Unorm_sRGB;
cad.blendingEnabled = YES;
cad.alphaBlendOperation = MTLBlendOperationAdd;
cad.sourceAlphaBlendFactor = MTLBlendFactorSourceAlpha;
cad.destinationAlphaBlendFactor = MTLBlendFactorDestinationAlpha;
cad.rgbBlendOperation = MTLBlendOperationAdd;
cad.sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
cad.destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
NSError *error = NULL;
_pipelineState = [_device newRenderPipelineStateWithDescriptor:pd error:&error];
}
- (void)drawInMTKView:(nonnull MTKView *)view
{
id <MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
id <MTLRenderCommandEncoder> renderEncoder =
[commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
[renderEncoder setFrontFacingWinding:MTLWindingCounterClockwise];
[renderEncoder setCullMode:MTLCullModeBack];
[renderEncoder setRenderPipelineState:_pipelineState];
[renderEncoder setVertexBuffer:_vertexBuffer offset:0 atIndex:0];
[renderEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
indexCount:3
indexType:MTLIndexTypeUInt16
indexBuffer:_indexBuffer
indexBufferOffset:0];
[renderEncoder endEncoding];
[commandBuffer presentDrawable:view.currentDrawable];
[commandBuffer commit];
}
#end
Shader.metal:
typedef struct {
float4 position [[position]];
} VertexOut;
vertex VertexOut
VertShader(const uint vertexID [[vertex_id]],
constant Vertex *vertices [[buffer(0)]])
{
VertexOut out;
Vertex v = vertices[vertexID];
out.position = (float4){v.position.x,v.position.y,0,1};
return out;
}
fragment half4
FragShader(VertexOut in [[stage_in]])
{
return half4(1,1,1,0.50f);
}
With that code, specifically the FragShader having 0.50f as the alpha value, I get a blank canvas:
If I change the alpha value to 0.51f:
fragment half4
FragShader(VertexOut in [[stage_in]])
{
return half4(1,1,1,0.51f);
}
I then get this:
Any help is appreciated!
Solved. The problem was that alphaToCoverageEnabled was set to true, while the render target texture type was NOT MTLTextureType2DMultisample. It appears the two work in tandem, but it's beyond my understanding how.
If not using multi-sampling, set alphaToCoverageEnabled to false.
Otherwise, make sure the render target is of type MTLTextureType2DMultisample.
If using MTKView, set the render target texture type by setting the sampleCount on the MTKView object:
_view = (MTKView *)self.view;
_view.sampleCount = 2;
and the render pipeline descriptor of the pipeline state:
MTLRenderPipelineDescriptor *pd = [[MTLRenderPipelineDescriptor alloc] init];
pd.sampleCount = 2;

Memory leak with CIColor spritekit

I created a class that would generate a hud item, this hud item can animate the resulting texture which is a gradient created using cicolor that is then saved into a uiimage which is in turn used for an sktexture. I've noticed now that i am getting a lot of memory growth in my app and running it through instruments has shown me this, but i can't for the life figure out whats going on:
Here's the error i get
You can't really see the issue so it's giving me 91.4% on this line of code:
animatedGraphic = [[SKSpriteNode alloc]initWithTexture:[[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]] color:[UIColor orangeColor] size:CGSizeMake(0, self.frame.size.height)];
animatedGraphic.anchorPoint = CGPointMake(0, 0.5);
animatedGraphic.zPosition = self.zPosition+1;
[self addChild:animatedGraphic];
Heres the code for the sktexture with a gradient:
-(SKTexture*)returnHorizontalGradientofSize:(CGSize)size
leftColor:(CIColor*)leftColor
rightColor:(CIColor*)rightColor{
CIContext *coreImageContext = [CIContext contextWithOptions:nil];
CIFilter *gradientFilter = [CIFilter filterWithName:#"CILinearGradient"];
[gradientFilter setDefaults];
CIVector *startVector = [CIVector vectorWithX:0 Y:size.height/2];
CIVector *endVector = [CIVector vectorWithX:size.width Y:size.height/2];
[gradientFilter setValue:startVector forKey:#"inputPoint0"];
[gradientFilter setValue:endVector forKey:#"inputPoint1"];
[gradientFilter setValue:leftColor forKey:#"inputColor0"];
[gradientFilter setValue:rightColor forKey:#"inputColor1"];
CGImageRef cgimg = [coreImageContext createCGImage:[gradientFilter outputImage]
fromRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *theImage = [UIImage imageWithCGImage:cgimg];
CFRelease(cgimg);
return [SKTexture textureWithImage:theImage];
}
Heres the code for the hud item:
#import "ItemHud.h"
#import "TextureList.h"
#import "UnlockController.h"
#interface ItemHud ()
#property (nonatomic) double scoreIncrement;
#property (nonatomic) double increment;
#property (nonatomic) double barIncrement;
#property (nonatomic) double updateIncrement;
#property (nonatomic) BOOL barAnimating;
#end
#implementation ItemHud
#synthesize theLabel;
#synthesize theLabelTwo;
#synthesize animatedGraphic;
#synthesize iconGraphic;
-(id)initWithImageNamed:(NSString *)ImageName
withLabel:(NSString *)LabelName
withLabelTwo:(NSString *)LabelNameTwo
withIconGraphic:(NSString *)iconGraphicName
withAnimatedGraphic:(BOOL)AnimatedGraphicName{
if (self = [super init]) {
if (ImageName)
{
self.size = [[TextureList sharedManager]returnTextureSize:ImageName];
self.texture = nil;
self.color = [UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:0.65];
self.userInteractionEnabled = NO;
_barAnimating = NO;
}
if (AnimatedGraphicName) {
animatedGraphic = [[SKSpriteNode alloc]initWithTexture:[[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]] color:[UIColor orangeColor] size:CGSizeMake(0, self.frame.size.height)];
animatedGraphic.anchorPoint = CGPointMake(0, 0.5);
animatedGraphic.zPosition = self.zPosition+1;
[self addChild:animatedGraphic];
}
if (iconGraphicName) {
if ([iconGraphicName isEqualToString:kGMHUDLevelIcon1] || [iconGraphicName isEqualToString:kGMHUDLevelIcon2] || [iconGraphicName isEqualToString:kGMHUDLevelIcon3] || [iconGraphicName isEqualToString:kGMHUDLevelIcon4]|| [iconGraphicName isEqualToString:kGMHUDLevelIcon5] || [iconGraphicName isEqualToString:kGMHUDLevelIcon6] || [iconGraphicName isEqualToString:kGMHUDLevelIcon7] || [iconGraphicName isEqualToString:kGMHUDLevelIcon8] || [iconGraphicName isEqualToString:kGMHUDLevelIcon9]) {
iconGraphic = [[SKSpriteNode alloc]initWithTexture:[SKTexture textureWithImageNamed:iconGraphicName] color:nil size:[[TextureList sharedManager]returnTextureSize:kGMHUDLevelIcon1]];
}
else{
iconGraphic = [[SKSpriteNode alloc]initWithTexture:[SKTexture textureWithImageNamed:iconGraphicName] color:nil size:[[TextureList sharedManager]returnTextureSize:iconGraphicName]];
}
iconGraphic.zPosition = self.zPosition+1;
[self addChild:iconGraphic];
[self setGraphicRight:NO];
}
if (LabelName) {
theLabel = [SKLabelNode labelNodeWithFontNamed:kFontName];
[theLabel setFontColor:[UIColor whiteColor]];
[theLabel setFontName:kFontName];
[theLabel setFontSize:kFontSizeMDMedium];
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeLeft];
[theLabel setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
theLabel.text = LabelName;
[self addChild:theLabel];
[self setHudDefaults:YES];
}
if (LabelNameTwo) {
theLabelTwo = [SKLabelNode labelNodeWithFontNamed:kFontName];
[theLabelTwo setFontColor:[UIColor whiteColor]];
[theLabelTwo setFontName:kFontName];
[theLabelTwo setFontSize:kFontSizeMDMedium];
[theLabelTwo setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeRight];
[theLabelTwo setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
theLabelTwo.text = LabelNameTwo;
[self addChild:theLabelTwo];
[self setHudDefaults:NO];
}
}
return self;
}
-(void)setBackgroundImage:(SKTexture*)theTexture{
self.texture = theTexture;
}
-(void)setHudDefaults:(BOOL)singleLabel{
theLabelTwo.position = CGPointMake(self.position.x+self.frame.size.width/2,self.position.y);
animatedGraphic.position = CGPointMake(-self.frame.size.width/2,self.position.y);
if (singleLabel) {
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
theLabel.position = CGPointMake(self.position.x,self.position.y);
}
else{
theLabel.position = CGPointMake(theLabelTwo.position.x-theLabelTwo.frame.size.width/2-20,self.position.y);
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeRight];
}
theLabel.zPosition = self.zPosition+1;
theLabelTwo.zPosition = self.zPosition+1;
}
-(void)setGraphicRight:(BOOL)placeRight{
if (placeRight) {
iconGraphic.position = CGPointMake(self.frame.size.width/2,-self.frame.size.height/4);
iconGraphic.zPosition = animatedGraphic.zPosition+1;
}
else{
iconGraphic.position = CGPointMake(-self.frame.size.width/2,-self.frame.size.height/4);
iconGraphic.zPosition = animatedGraphic.zPosition+1;
}
}
-(void)setBarProgress:(int)flowerTarget currentFlowers:(int)currentFlowers{
double increment = (double)flowerTarget/100;
//NSLog(#"increment is %f",increment);
double barIncrement = (double)self.frame.size.width/100;
//NSLog(#"BAR increment is %f",barIncrement);
double barState = (barIncrement/increment)*currentFlowers;
//NSLog(#"BAR state is %f",barState);
/*if (animatedGraphic.frame.size.width >= self.frame.size.width && !_barAnimating) {
_barAnimating = YES;
[self animateBar:YES];
}
else if (animatedGraphic.frame.size.width < self.frame.size.width && _barAnimating){
_barAnimating = NO;
[self animateBar:NO];
}*/
animatedGraphic.size = CGSizeMake(barState, self.frame.size.height);
}
-(void)setBarValues:(int)startValue increment:(int)increment nextObject:(int)nextObject{
//NSLog(#"0:Totalscore is %i",[[UserDetails sharedManager]userTotalScore]);
//NSLog(#"1:StartValue %i",startValue);
//NSLog(#"2:Increment %i",increment);
//NSLog(#"3:Nextobject %i",nextObject);
_scoreIncrement = (double)startValue/(double)nextObject;
//NSLog(#"increment is %f",increment);
_barIncrement = (double)self.frame.size.width/100;
//NSLog(#"bar increment is %f",barIncrement);
_updateIncrement = ((double)startValue/_scoreIncrement)/100;
//NSLog(#"update increment is %f",updateIncrement);
//NSLog(#"4:Animate %f",_barIncrement/_updateIncrement*increment);
animatedGraphic.size = CGSizeMake(_barIncrement/_updateIncrement*increment, self.frame.size.height);
}
-(void)updateBarProgress:(int)update{
animatedGraphic.size = CGSizeMake(_barIncrement/_updateIncrement*update, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}
-(void)setBarValues:(int)startValue nextObject:(int)nextObject animated:(BOOL)animated{
// start value is difference between unlock score and current value
// next object is score to unlock item
// all unlocks done
if ([[UnlockController sharedManager]allunlocksOpen]) {
theLabel.text = #"ALL ITEMS UNLOCKED";
return;
}
__block int count = 0;
double increment = (double)startValue/(double)nextObject;
//NSLog(#"increment is %f",increment);
double countUp = nextObject-startValue;
//NSLog(#"countup is %f",countUp);
double barIncrement = (double)self.frame.size.width/100;
//NSLog(#"bar increment is %f",barIncrement);
double updateIncrement = ((double)startValue/increment)/100;
//NSLog(#"update increment is %f",updateIncrement);
if (!animated) {
animatedGraphic.size = CGSizeMake(barIncrement/updateIncrement*startValue, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}
else{
SKAction *delay = [SKAction waitForDuration:0.0];
SKAction *animateCount = [SKAction runBlock:^{
count++;
animatedGraphic.size = CGSizeMake(barIncrement*count, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}];
SKAction *animateSequence = [SKAction sequence:#[animateCount,delay]];
SKAction *repeatSequence = [SKAction repeatAction:animateSequence count:(double)countUp/updateIncrement];
[animatedGraphic runAction:repeatSequence completion:^{
}];
}
}
-(void)animateBar:(BOOL)animate{
SKAction *delay = [SKAction waitForDuration:0.15];
SKAction *changeToAnimateBar = [SKAction runBlock:^{
animatedGraphic.texture = [[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:244.0/255.0 blue:155.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]];
}];
SKAction *changeToDefaultBar = [SKAction runBlock:^{
animatedGraphic.texture = [[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]];
}];
SKAction *animateSequence = [SKAction sequence:#[changeToAnimateBar,delay,changeToDefaultBar,delay]];
SKAction *animatingBarLoop = [SKAction repeatActionForever:animateSequence];
if (animate) {
[self runAction:animatingBarLoop withKey:#"animatingBar"];
}
else{
[self removeActionForKey:#"animatingBar"];
[self runAction:changeToDefaultBar withKey:#"defaultBar"];
}
}
This turned out to be an issue with the AGSpriteButton class which was hogging memory and therefore eventually causing a crash when an advert loaded, you can find a fix here:
SKScene Fails to deallocate memory resulting in bounded memory growth

Moving objects in an array using UITouch SpriteKit

I'm trying to move SKSpritenode in an array like a scrollbar where all objects move together according to the move location:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
NSEnumerator *e = [_blockStream objectEnumerator];
PBAIceBlock *block;
while (block = [e nextObject])
{
//this says the expresion is not assignable
block.position.y += location.y;
}
}
Where the comments says, I get an error, could some one please point me in the right direction on how to implement something like this?
Using Sprite kit in xcode 5?
A solution is to create a CGPoint to store a value. set that value in touchesBegan, then:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
int yOFFSET = location.y - _touchLocation.y ;
NSLog(#"yOFFSET : %d", yOFFSET);
NSEnumerator *e = [_blockStream objectEnumerator];
PBAIceBlock *block;
while (block = [e nextObject]) {
CGPoint _center = block.position;
_center.y += yOFFSET;
block.position = _center;
}
_touchLocation = location;
}
This problem happened because you cannot call the position.y specifically.

How to setPosition menu from the screen?

How can I set my menu Sprites in the center of the screen with the usual look for menu
CCSize size = CCDirector::sharedDirector()->getWinSize();
sprite ->setPosition(ccp(size.width, size.height));
Please help me with the (ccp(?,?))
Sprites: Start, Options, Quit for game menu
#include "MenuScene.h"
#include "cocos2d.h"
USING_NS_CC;
using namespace cocos2d;
CCSprite *car;
CCScene* MenuScene::scene()
{
CCScene *scene = CCScene::create();
MenuScene *layer = MenuScene::create();
scene->addChild(layer);
return scene;
}
// on "init" you need to initialize your instance
bool MenuScene::init()
{
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
this->setTouchEnabled(true);
//this->schedule( schedule_selector(MenuScene::update) );
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
// add a "close" icon to exit the progress. it's an autorelease object
// CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
// "CloseNormal.png",
// "CloseSelected.png",
// this,
// menu_selector(MenuScene::menuCloseCallback));
//
// pCloseItem->setPosition(ccp(origin.x + visibleSize.width -
pCloseItem->getContentSize().width ,
// origin.y +
pCloseItem->getContentSize().height));
// create menu, it's an autorelease object
// CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
// pMenu->setPosition(CCPointZero);
// this->addChild(pMenu, 1);
// 3. add sprite below...
CCSprite *menuLayout = CCSprite::create("sky.png");
menuLayout->setPosition(ccp(size.width/2, size.height/2));
this->addChild(menuLayout, -1);
float aX = size.width / menuLayout->getContentSize().width;
float aY = size.height / menuLayout->getContentSize().height;
menuLayout->setScaleX(aX);
menuLayout->setScaleY(aY);
return true;
}
//callfuncN_selector(MainScene::spriteMoveFinished)
//backcalls the function spriteMoveFinished()
void MenuScene::spriteMoveFinished(CCNode* pSender)
{
CCSprite *sprite = (CCSprite *)pSender;
this->removeChild(sprite, true);
}
void MenuScene::Menus()
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCMenuItemImage *startItem = CCMenuItemImage::create("sprite.png",
"sprite.png",this,menu_selector(MenuScene::menuCloseCallback));
startItem->setPosition(ccp(590, 450));
float aX = size.width / startItem->getContentSize().width;
float aY = size.height / startItem->getContentSize().height;
// startItem->setScaleX(aX);
// startItem->setScaleY(aY);
CCMenuItemImage *extraItem = CCMenuItemImage::create("sprite2.png",
"sprite2.png",this,menu_selector(MenuScene::menuCloseCallback));
extraItem->setPosition(ccp(590,350));
//float bX = size.width / extraItem->getContentSize().width;
//float bY = size.height / extraItem->getContentSize().height;
//extraItem->setScaleX(bX);
//extraItem->setScaleY(bY);
CCMenuItemImage *optionsItem = CCMenuItemImage::create("options.png",
"options.png",this,menu_selector(MenuScene::menuCloseCallback));
optionsItem->setPosition(ccp(590, 250));
//float cX = size.width / optionsItem->getContentSize().width;
//float cY = size.height / optionsItem->getContentSize().height;
//optionsItem->setScaleX(cX);
//optionsItem->setScaleY(cY);\
CCMenuItemImage *quitItem = CCMenuItemImage::create("quit.png",
"quit.png",this,menu_selector(MenuScene::menuCloseCallback));
quitItem->setPosition(ccp(590, 150));
// float dX = size.width / quitItem->getContentSize().width;
// float dY = size.height / quitItem->getContentSize().height;
// quitItem->setScaleX(dX);
// quitItem->setScaleY(dY);
CCMenu* pMenu = CCMenu::create(startItem, extraItem, optionsItem, quitItem,
NULL);
pMenu->setPosition(0,0);
this->addChild(pMenu, 0);
}
void MenuScene::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
Menus();
}
void MenuScene::ccTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
Menus();
}
void MenuScene::ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
}
void MenuScene::ccTouchesCancelled(cocos2d::CCSet* touches, cocos2d::CCEvent*
event){
}
void MenuScene::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
/* namespace cocos2d */
If you wish to position the menu at the center of the screen you must provide the center co-ordinates in ccl
sprite ->setPosition(ccp(size.width/2, size.height/2));
First you get window size...
CGSize Window_size=[[CCDirector sharedDirector]winSize];
Now set CCMenuItem in CCMenu With position...
CCMenuItem *Minus_Menu_item = [CCMenuItemImage itemWithNormalImage:#"ButtonMinus.png" selectedImage:#"ButtonMinus.png" disabledImage:#"ButtonNum1.png" target:self selector:#selector(Minus_Button:)];
Minus_Menu_item.position=ccp(180, 200);
Menu_Minus=[CCMenu menuWithItems:Minus_Menu_item, nil];
Menu_Minus.position = CGPointZero;
[self addChild:Menu_Minus];

resize UIImage in table cell programmatically

how can i resize the UIImage in table cell
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 5.0;
cell.imageView.frame=CGRectMake(0, 0, 20, 30);
cell.imageView.image =[UIImage imageNamed:#"Diseases.png"];
it is not working
Use this method, pass the size and image, and get the image then show in cell
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
You can also make your custom UITableViewCell, and design as you want to look it
This worked for me.
///////////////////////////////// TO RESIZE IMAGE //////////////////////////////////
////////// FIRST WRITE DESIRED SIZE AND CALL BELOW FINCTION ///////
CGSize newSize ;
newSize.width = 30;
newSize.height = 30;
UIImage *imgSelectedNew = [self imageWithImage:savedImage scaledToSize:newSize];
- (UIImage*)imageWithImage:(UIImage*)sourceImage scaledToSize:(CGSize)targetSize
{
//UIImage *sourceImage = sourceImage;//= self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// this is actually the interesting part:
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil)
NSLog(#"could not scale image");
return newImage ;
}
well m also n indorian , Gud to see the other one !!! :)

Resources