memory leak while making graph of functions in calculator iPad - objective-c

i am developing a scientific calculator for iPad . I am trying to draw functions creating a graphical representation . but i a have a memory leak when i draw a function of second degree for example x^2 . I was wondering if you could help solve the following memory leak,please? I would appreciate any help. The button that opens the screen with the function to be drawn has this code :
userIsInTheMiddleOfTypingANumber = YES;
graphVC.expression =[NSMutableArray arrayWithObject:[NSString
stringWithFormat:#"%#",#"$x**2"] ];
[self prepareToSolve];
graphVC=[[GraphViewController alloc] initWithNibName:#"GraphViewController"
bundle:Nil];
[self presentModalViewController:graphVC animated:YES];
Then in the GraphViewController i set the expression with the code:
- (void)viewDidLoad
{
[graphView reset];
[graphView setNeedsDisplay];
currentColumn = [NSMutableString string];
substitutions = [NSMutableDictionary dictionary];
eval = [DDMathEvaluator sharedMathEvaluator];
[currentColumn setString:[expression objectAtIndex:0]];
}
and then the method expressionResultForXValue leaks
- (double)expressionResultForXValue:(NSNumber*)x requestor:(GraphView *)graphView {
[substitutions setValue:x forKey:#"x"];
return [[eval evaluateString:currentColumn withSubstitutions:substitutions]
doubleValue]; //[CalculatorBrain evaluateExpression:self.expression
usingVariableValues:variableValues];
}
even though in the viewDidUnload method i set - [expression release];
The expressionResultForXValue method is called many times by the UIView GraphView by the drawrect method:
- (void)drawRect:(CGRect)rect {
CGPoint midpoint;
midpoint.x = self.bounds.origin.x + self.bounds.size.width/2 + originOffset.x;
midpoint.y = self.bounds.origin.y + self.bounds.size.height/2 + originOffset.y;
[[UIColor whiteColor] setStroke];
[AxesDrawer drawAxesInRect:self.bounds originAtPoint:midpoint
scale:self.scale*self.contentScaleFactor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5);
CGContextBeginPath(context);
for (CGFloat i = 0; i <= self.bounds.size.width; i++) {
CGPoint nextPointInViewCoordinates;
nextPointInViewCoordinates.x = i;
CGPoint nextPointInGraphCoordinates;
nextPointInGraphCoordinates.x = (nextPointInViewCoordinates.x - midpoint.x)/(self.scale
* self.contentScaleFactor);
nextPointInGraphCoordinates.y = ([self.delegate expressionResultForXValue:[NSNumber
numberWithDouble:nextPointInGraphCoordinates.x]
requestor:self]);
nextPointInViewCoordinates.y = midpoint.y - (nextPointInGraphCoordinates.y * self.scale
* self.contentScaleFactor);
if (i == 0) {
CGContextMoveToPoint(context, nextPointInViewCoordinates.x,
nextPointInViewCoordinates.y);
} else {
CGContextAddLineToPoint(context,
nextPointInViewCoordinates.x,nextPointInViewCoordinates.y);
}
}
[[UIColor yellowColor] setStroke];
CGContextDrawPath(context, kCGPathStroke);
}
The memory leak i get is :
Leaked Object # Address Size Responsible Library Responsible Frame
_DDFunctionExpression 1020 < multiple > 15,94 KB Rechemaschinn
+[DDExpression functionExpressionWithFunction:arguments:error:]
NSDecimalNumber 1018 < multiple > 15,91 KB Foundation -[NSDecimalNumberPlaceholder initWithDecimal:]
_DDNumberExpression 1020 < multiple > 15,94 KB Rechemaschinn +[DDExpression numberExpressionWithNumber:]
NSArray 1020 < multiple > 15,94 KB Rechemaschinn -[_DDFunctionExpression initWithFunction:arguments:error:]
_DDVariableExpression 1020 < multiple > 15,94 KB Rechemaschinn +[DDExpression variableExpressionWithVariable:]
__NSCFString 1019 < multiple > 15,92 KB Foundation -[NSPlaceholderString initWithCharacters:length:]
Thank you in advance.

Related

Issues with SpriteKit in Xcode 7 and IOS 9

My game app that was working perfectly fine on IOS 8 (built with Xcode 6) is all of sudden experiencing many issues when built using Xcode 7 with IOS 9.
Here is how the game used to look. (How it should look).
Here is it running on IOS 9 (broken)
GAME SCENE CODE
Code for creating the Game Board in Game Scene
-(void) createBoard {
self.buttons=[NSMutableArray new];
if (self.boardBlur != nil ) {
[self.boardBlur removeAllChildren];
}
self.backgroundColor=[UIColor clearColor];
// Use for Christmas Easter egg
/* NSString *snowPath = [[NSBundle mainBundle] pathForResource:#"SnowParticle" ofType:#"sks"];
SKEmitterNode *snow = [NSKeyedUnarchiver unarchiveObjectWithFile:snowPath];
snow.particlePositionRange=CGVectorMake(self.frame.size.width, 20);
snow.position=CGPointMake(self.frame.size.width/2,self.frame.size.height);
snow.zPosition=-3;
[self addChild:snow];*/
if (self.boardFrame != nil) {
[self.boardFrame removeFromParent];
[self.boundingBox removeFromParent];
}
self.boardFrame = [SKSpriteNode spriteNodeWithImageNamed:#"gameBoard2"];
self.boardFrame.color= self.level.baseColor;
self.boardFrame.colorBlendFactor=1.0;
self.boardFrame.alpha = .7;
self.boardFrame.zPosition=-1;
// self.boardFrame.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+40);
self.boardFrame.size=self.size;
if (self.boardBlur == nil) {
self.boardBlur=[[SKEffectNode alloc]init];
self.boardBlur.filter=[CIFilter filterWithName:#"CIGaussianBlur"];
[self.boardBlur.filter setDefaults];
[self.boardBlur.filter setValue:#5.0 forKey:kCIInputRadiusKey];
self.boardBlur.shouldEnableEffects=NO;
self.boardBlur.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+40);
[self addChild:self.boardBlur];
}
[self.boardBlur addChild:self.boardFrame];
[self displayMessage:self.level.name color:[UIColor whiteColor]];
[self createHUD];
CGRect playSurface=CGRectInset(self.frame, 36,36);
self.gridSize=fmin(playSurface.size.width,playSurface.size.height)/(fmax(self.level.width,self.level.height));
if (self.gridSize > 60) {
self.gridSize=60;
}
CGRect oldPlaySurface =playSurface;
playSurface=CGRectMake(0,0,self.gridSize*self.level.width,self.gridSize*self.level.height);
self.boardFrame.size=CGRectInset(playSurface, -24, -24).size;
self.boardBlur.zPosition=-2;
self.boundingBox=[SKShapeNode shapeNodeWithRect:CGRectInset(self.boardFrame.frame,self.gridSize/1.7,self.gridSize/1.7) cornerRadius:7.0];
self.boundingBox.strokeColor=[SKColor clearColor];
self.boundingBox.position=self.boardBlur.position;
self.boundingBox.zPosition=-5;
[self addChild:self.boundingBox];
self.ballSize=self.gridSize-6;
self.enlargeAction=[SKAction resizeToWidth:self.ballSize+5 height:self.ballSize+5 duration:0.2];
self.shrinkAction=[SKAction resizeToWidth:self.ballSize height:self.ballSize duration:0.2];
self.enlargeInAction=[SKAction resizeToWidth:self.ballSize height:self.ballSize duration:0.3];
self.shrinkOutAction=[SKAction resizeToWidth:0 height:0 duration:0.3];
CGFloat horizontalSpace = (playSurface.size.width-self.gridSize*self.level.width);
CGFloat verticalSpace = (playSurface.size.height-self.gridSize*self.level.height);
self.topOffset=80+verticalSpace/2+(oldPlaySurface.size.height-playSurface.size.height)/2;
self.leftOffset=40+horizontalSpace/2+(oldPlaySurface.size.width-playSurface.size.width)/2;
for (int y=0; y < self.level.height; y++) {
for (int x = 0; x < self.level.width; x++) {
//SKSpriteNode *backgroundButtonNode = [SKSpriteNode spriteNodeWithTexture:dotTexture];
SKShapeNode *backgroundButtonNode=[SKShapeNode shapeNodeWithCircleOfRadius:0.5];
// backgroundButtonNode.size=ballSize;
backgroundButtonNode.userInteractionEnabled=NO;
backgroundButtonNode.zPosition=0;
backgroundButtonNode.fillColor=[UIColor whiteColor];
// backgroundButtonNode.colorBlendFactor=1.0;
backgroundButtonNode.position=[self.boardFrame convertPoint:CGPointMake(self.leftOffset+(self.gridSize*x)+self.ballSize/2,self.topOffset+(self.gridSize*y)+self.ballSize/2) fromNode:self];
[self.boardFrame addChild: backgroundButtonNode];
}
}
CGFloat menuiconsize=fmin(self.ballSize, 60.0);
CGFloat menuWidth=fmin(self.boardFrame.size.width-40,420);
if (self.menuBar != nil) {
[self.menuBar removeFromParent];
}
self.menuBar=[[MenuBar alloc]initWithSize:CGSizeMake(menuWidth,self.ballSize+12) iconSize:CGSizeMake(menuiconsize,menuiconsize) Level:self.level];
self.menuBar.delegate=self;
[self addChild:self.menuBar];
self.menuBar.position=CGPointMake(self.frame.size.width/2-(menuWidth)/2, self.topOffset-menuiconsize-40);
self.menuBar.userInteractionEnabled=YES;
self.gameOver=NO;
}
Code for the HUD (Stars, Goal...)
-(void) createHUD {
if (self.topHud == nil) {
self.topHud=[SKShapeNode shapeNodeWithRect:CGRectMake(-2,self.frame.size.height-62,self.frame.size.width+2,64)];
self.topHud.fillColor=[UIColor clearColor];
self.topHud.strokeColor=[UIColor clearColor];
self.topHud.lineWidth=0;
[self addChild:self.topHud];
UIColor *textColor=[self.level textColor];
self.scoreLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.scoreLabel.fontSize=20;
self.scoreLabel.alpha = 1;
self.scoreLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeRight;
self.scoreLabel.fontColor=textColor;
self.scoreLabel.position=CGPointMake(self.frame.size.width-8,self.frame.size.height-25);
self.score=0;
[self.topHud addChild:self.scoreLabel];
self.highScoreLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.highScoreLabel.fontSize=20;
self.highScoreLabel.alpha = 1;
self.highScoreLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeRight;
self.highScoreLabel.fontColor=textColor;
self.highScoreLabel.position=CGPointMake(self.frame.size.width-8,self.frame.size.height-50);
//self.highScore=0;
[self.topHud addChild:self.highScoreLabel];
[self updateScore];
self.doughLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.doughLabel.fontColor=textColor;
self.doughLabel.fontSize=20;
self.doughLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeCenter;
self.doughLabel.position=CGPointMake(self.frame.size.width/2, 20);
[self coinBalanceChanged:nil];
[self addChild:self.doughLabel];
self.progressNode=[SKCropNode new];
self.progressNode.zPosition=1;
SKNode *dimStarsNode=[SKNode new];
SKSpriteNode *maskNode=[SKSpriteNode spriteNodeWithColor:[UIColor blackColor] size:CGSizeMake(66,24)];
maskNode.position=CGPointMake(-42, 0);
// self.progressNode.maskNode=maskNode;
for (int i=0;i<3;i++) {
SKSpriteNode *starNode=[SKSpriteNode spriteNodeWithImageNamed:#"SugarCookie"];
starNode.size=CGSizeMake(20,20);
starNode.position=CGPointMake(i*22,0);
[self.progressNode addChild:starNode];
starNode=[SKSpriteNode spriteNodeWithImageNamed:#"SugarCookie"];
starNode.size=CGSizeMake(20,20);
starNode.zPosition=1;
starNode.alpha=0.3;
starNode.position=CGPointMake(i*22,0);
[dimStarsNode addChild:starNode];
}
self.progressNode.maskNode= maskNode;
// self.progressNode.maskNode=maskNode;
self.progressNode.position=CGPointMake(22, self.frame.size.height-18);
dimStarsNode.position=CGPointMake(22, self.frame.size.height-18);
dimStarsNode.zPosition=0;
[self addChild:dimStarsNode];
[self addChild:self.progressNode];
self.goalLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.goalLabel.fontSize=20;
self.goalLabel.alpha = 1;
self.goalLabel.fontColor=textColor;
self.goalLabel.position=CGPointMake(12,self.frame.size.height-50);
self.goalLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeLeft;
self.goalLabel.text=[NSString stringWithFormat:#"Goal: %ld",(long)self.level.targetScore];
[self addChild:self.goalLabel];
self.storeButton=[[GameButtonNode alloc]initWithColor:self.level.baseColor strokeColor:[self.level levelColorWithBrightnessDelta:0.3 alpha:1.0] imageName:#"store" radius:25 physics:NO delegate:self];
self.storeButton.position=CGPointMake(self.frame.size.width-40,35);
[self addChild:self.storeButton];
self.menuButton=[[GameButtonNode alloc]initWithColor:self.level.baseColor strokeColor:[self.level levelColorWithBrightnessDelta:0.3 alpha:1.0] imageName:#"menuButton" radius:25 physics:NO delegate:self];
self.bottomMenuNode=[SKShapeNode shapeNodeWithRect:CGRectMake(5, 30, 180, 60) cornerRadius:7.0];
self.bottomMenuNode.strokeColor=[UIColor clearColor];
self.bottomMenuNode.fillColor=[self.level levelColorWithBrightnessDelta:-0.6 alpha:0.2];
self.bottomMenuNode.zPosition=6;
self.homeButton=[[GameButtonNode alloc]initWithColor:self.level.baseColor strokeColor:[self.level levelColorWithBrightnessDelta:0.3 alpha:1.0] imageName:#"homeButton" radius:25 physics:NO delegate:self];
self.homeButton.position=CGPointMake(35,60);
[self.bottomMenuNode addChild:self.homeButton];
self.menuReplayButton=[[GameButtonNode alloc]initWithColor:self.level.baseColor strokeColor:[self.level levelColorWithBrightnessDelta:0.3 alpha:1.0] imageName:#"replayButton" radius:25 physics:NO delegate:self];
self.menuReplayButton.position=CGPointMake(95,60);
[self.bottomMenuNode addChild:self.menuReplayButton];
NSString *soundImage=[self soundImage];
self.soundButton=[[GameButtonNode alloc]initWithColor:self.level.baseColor strokeColor:[self.level levelColorWithBrightnessDelta:0.3 alpha:1.0] imageName:soundImage radius:25 physics:NO delegate:self];
self.soundButton.position=CGPointMake(155,60);
[self.bottomMenuNode addChild:self.soundButton];
self.bottomMenuNode.position=CGPointMake(0, 0);
self.bottomMenuNode.hidden=YES;
self.bottomMenuNode.xScale=0.1;
self.bottomMenuNode.yScale=0.1;
[self.menuButton addChild:self.bottomMenuNode];
self.menuButton.position=CGPointMake(40,35);
self.menuButton.zPosition=7;
[self addChild:self.menuButton];
}
}
Code for GameBoardNode
-(instancetype) initWithColor:(UIColor *)color strokeColor:(UIColor *) strokeColor imageName:(NSString *)imageName radius:(CGFloat)radius physics:(BOOL)physics delegate:(id<GameButtonNodeDelegate>)delegate {
if (self=[super init]) {
self.strokeColor=strokeColor;
self.ball=[SKShapeNode shapeNodeWithCircleOfRadius:radius];
self.ball.fillColor=color;
self.ball.strokeColor=strokeColor;
self.ball.lineWidth=3.0;
self.ball.zPosition=0;
self.touchDelegate=delegate;
[self addChild:self.ball];
self.icon=[SKSpriteNode spriteNodeWithImageNamed:imageName];
self.icon.size=CGSizeMake(30, 30);
self.icon.zPosition=0;
self.enabled=YES;
[self addChild:self.icon];
if (physics) {
self.physicsBody=[SKPhysicsBody bodyWithCircleOfRadius:radius ];
self.physicsBody.affectedByGravity=YES;
}
self.userInteractionEnabled=YES;
self.fadeIn=[SKAction fadeInWithDuration:0.3];
self.fadeOutRemove=[SKAction sequence:#[[SKAction waitForDuration:0.2],[SKAction fadeOutWithDuration:0.3],[SKAction removeFromParent]]];
}
return self;
}
LEVEL SELECT
The only issue with this view is the background image (blue gradient) appears and then fades away.
The background image is set up in the storyboard.
Most Images are coming from Images.xcassets folder.
All images are png.
Bitcode is off (if that makes a difference)
Any other code or images, just ask.
How can I fix this problem and get my game working properly again?
iOS 9 cares more about zPosition than iOS 8 did. In the past if you didn't set the zPosition iOS8 would do a really good job of assuming what you wanted. In iOS9 it doesn't care and will render it however it wants.
I have also noticed leaving it at zero is also very bad. For instance if you have a node at 0 and add a child with a zPosition of 0...they both are 0 and iOS9 will pick which it should render first. If I am correct this should get your top hud showing back up again.
if (self.topHud == nil) {
self.topHud=[SKShapeNode shapeNodeWithRect:CGRectMake(-2,self.frame.size.height-62,self.frame.size.width+2,64)];
self.topHud.fillColor=[UIColor clearColor];
self.topHud.strokeColor=[UIColor clearColor];
self.topHud.lineWidth=0;
self.topHud.zPosition = 100;//added zPosition
[self addChild:self.topHud];
UIColor *textColor=[self.level textColor];
self.scoreLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.scoreLabel.fontSize=20;
self.scoreLabel.alpha = 1;
self.scoreLabel.zPosition = 1;//added zPosition
self.scoreLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeRight;
self.scoreLabel.fontColor=textColor;
self.scoreLabel.position=CGPointMake(self.frame.size.width-8,self.frame.size.height-25);
self.score=0;
[self.topHud addChild:self.scoreLabel];
self.highScoreLabel=[SKLabelNode labelNodeWithFontNamed:#"Blow"];
self.highScoreLabel.fontSize=20;
self.highScoreLabel.alpha = 1;
self.highScoreLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeRight;
self.highScoreLabel.fontColor=textColor;
self.highScoreLabel.position=CGPointMake(self.frame.size.width-8,self.frame.size.height-50);
self.highScoreLabel.zPosition = 1;//added zPosition
//self.highScore=0;
[self.topHud addChild:self.highScoreLabel];
Note 4 zPositions added. I hope that helps get things going in the right direction.

How control memory usage when applying CIFilters?

When I apply CIFilters to images the memory usage keeps growing and I don't know what to do.
I've tried everything I could:
using #autoreleasepool:
- (UIImage *)applySepiaToneTo:(UIImage *)img //Sepia
{
#autoreleasepool
{
CIImage *ciimageToFilter = [CIImage imageWithCGImage:img.CGImage];
CIFilter *sepia = [CIFilter filterWithName:#"CISepiaTone"
keysAndValues: kCIInputImageKey, ciimageToFilter,
#"inputIntensity", #1.0, nil];
return [self retrieveFilteredImageWithFilter:sepia];
}
}
- (UIImage *)retrieveFilteredImageWithFilter:(CIFilter *)filtro
{
#autoreleasepool
{
CIImage *ciimageFiltered = [filtro outputImage];
CGImageRef cgimg = [_context createCGImage:ciimageFiltered
fromRect:[ciimageFiltered extent]];
UIImage *filteredImage = [UIImage imageWithCGImage:cgimg];
CGImageRelease(cgimg);
return filteredImage;
}
}
I'm also downsizing the image to be filtered and doing the filtering in a background thread:
- (void)filterWasSelected:(NSNotification *)notification
{
self.darkeningView.alpha = 0.5;
self.darkeningView.userInteractionEnabled = YES;
[self.view bringSubviewToFront:self.darkeningView];
[self.activityIndic startAnimating];
[self.view bringSubviewToFront:self.activityIndic];
int indice = [notification.object intValue];
__block NSArray *returnObj;
__block UIImage *auxUiimage;
if(choosenImage.size.width == 1280 || choosenImage.size.height == 1280)
{
UIImageView *iv;
if(choosenImage.size.width >= choosenImage.size.height)
{
float altura = (320 * choosenImage.size.height)/choosenImage.size.width;
iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,altura)];
iv.image = choosenImage;
}
else
{
float largura = (choosenImage.size.width * 320)/choosenImage.size.height;
iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,largura,320)];
iv.image = choosenImage;
}
UIGraphicsBeginImageContextWithOptions(iv.bounds.size, YES, 0.0);
[iv.layer renderInContext:UIGraphicsGetCurrentContext()];
auxUiimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
else
auxUiimage = choosenImage;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
if(artisticCollection)
returnObj = [self.filterCoordinator setupFilterArtisticType:indice toImage:auxUiimage];
else
returnObj = [self.filterCoordinator setupFilterOldOrVintageType:indice toImage:auxUiimage];
dispatch_async(dispatch_get_main_queue(), ^{
self.darkeningView.alpha = 0.3;
self.darkeningView.userInteractionEnabled = NO;
[self.activityIndic stopAnimating];
[self.view bringSubviewToFront:stageBackground];
[self.view bringSubviewToFront:stage];
[self.view bringSubviewToFront:self.filtersContainerView];
[self.view bringSubviewToFront:self.framesContainerView];
[self.view bringSubviewToFront:self.colorsContainerView];
if(returnObj)
{
auxUiimage = [returnObj firstObject];
NSLog(#"filtered image width = %f and height = %f", auxUiimage.size.width, auxUiimage.size.height);
returnObj = nil;
choosenImageContainer.image = auxUiimage;
}
});
});
}
I've also tried creating the context using the contextWithEAGLContext method, nothing changed.
I've researched a lot including stack overflow and found nothing.
Until I place the image in the image view (the image comes from the photo album) I'm only using 23 mega of memory, when I apply a filter, the use jumps to 51 mega and does not comes down. If I continue to apply other filters the memory usage only grows.
There's no linking in my app, I've checked in Instruments.
Also the bringSubviewToFront methods are not responsible, I've checked.
It's in the creation of the CIImage followed by the creation of the CIFilter object.
I know that in the process of applying the filter data is loaded into memory, but how to clean the memory after applying the filter?
Is there any secret that I'm not aware of?? Please help

Screenshot code working perfectly in Simulator but not in iOS Device

This is my code for screenshot to save in library or do email. The problem is, it is working perfectly in Simulator but when i run this code in Device whatever on screen it only gets white image. I have tried with iOS 5 and iOS 6 both but no luck
What should be the reason Where i am wrong
NSInteger myDataLength = 320 * 430 * 4;
GLubyte *buffer1 = (GLubyte *) malloc(myDataLength);
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
//Read image memory form OpenGL
glReadPixels(0, 50, 320, 430, GL_RGBA, GL_UNSIGNED_BYTE, buffer1);
//Invert result image buffer into secondary buffer
for(int y = 0; y < 430; y++) {
for(int x = 0; x < 320 * 4; x++) {
buffer2[(429 - y) * 320 * 4 + x] = buffer1[y * 4 * 320 + x];
}
}
//Create bitmap context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef destContext = CGBitmapContextCreate(buffer2, 320, 430, 8, 320 * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
//Get image from context
CGImageRef resultContext = CGBitmapContextCreateImage(destContext);
UIImage *resultImg = [UIImage imageWithCGImage: resultContext];
CGImageRelease(resultContext);
//Send to mail or Save to PhotoLibrary
if (sendMail) {
[self emailImage: resultImg];
} else {
UIImageWriteToSavedPhotosAlbum(resultImg, nil, nil, nil);
}
//Release allocated memory
// [resultImg release];
free(buffer2);
free(buffer1);
CGContextRelease(destContext);
CGColorSpaceRelease(colorSpace);
is there any class i am using which is supported by Simulator and not the device If it so then which one because as far as i search i found nothing like that.
I have found that My above code is perfect and the issue is not lie here.actually the problem is with
eaglLayer.drawableProperties
I have changed from this code
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO],
kEAGLDrawablePropertyRetainedBacking,
kEAGLColorFormatRGB565,
kEAGLDrawablePropertyColorFormat, nil];
To this
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],
kEAGLDrawablePropertyRetainedBacking,
kEAGLColorFormatRGB565,
kEAGLDrawablePropertyColorFormat, nil];
I just set
kEAGLDrawablePropertyRetainedBacking = YES
And thanks GOD it is working fine.
but dont know why if any one know please let me know
try this one, it works perfect for me on the device:
+ (UIImage *)imageFromView:(UIView *)view inRect:(CGRect)rect {
CGFloat screenScale = [[UIScreen mainScreen] scale];
if ([view respondsToSelector:#selector(contentSize)]) {
UIScrollView *scrollView = (UIScrollView *)view;
UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, screenScale);
} else {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, screenScale);
}
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
[view.layer renderInContext:resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, CGRectMake(rect.origin.x*screenScale, rect.origin.y*screenScale, rect.size.width*screenScale, rect.size.height*screenScale))];
UIGraphicsEndImageContext();
return [image imageScaledToSize:CGSizeMake(rect.size.width, rect.size.height)];
}
- (UIImage *)imageScaledToSize:(CGSize)newSize {
if ((self.size.width == newSize.width) && (self.size.height == newSize.height)) {
return self;
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

Issue with scroll view and accessing its subviews

I have a scroll view that contains image view sized 68x78:
As you could see, all that images except from the centered one have a shadow. It changes when user scrolls, center image is always clear. It goes perfect until for the left edge image:
Here is the code:
-(void) buildSlideView{
fotosJugadores = [[NSArray alloc] initWithObjects:#"cara5.png", #"cara7.png", #"cara8.png", #"cara9.png", #"cara11.png", #"cara13.png", #"cara14.png", #"cara15.png", #"cara18.png",#"cara19.png", #"cara20.png", #"cara32.png",#"cara44.png",#"cara51.png", #"cara100.png", #"cara101.png", #"cara102.png",#"cara103.png", #"cara104.png", #"cara105.png",#"cara106.png",#"cara107.png", nil];
numberOfViews = [fotosJugadores count];
for (int i = 0; i < [fotosJugadores count]; i++) {
UIImage *myImage = [UIImage imageNamed:[fotosJugadores objectAtIndex:i]];
CGFloat yOrigin = i * (myImage.size.width+3) + 120;
UIImageView *awesomeView = [[UIImageView alloc] initWithFrame:CGRectMake(yOrigin, 0, myImage.size.width, myImage.size.height)];
awesomeView.tag = i;
awesomeView.image = myImage;
awesomeView.alpha = 0.5f;
awesomeView.backgroundColor = [UIColor blackColor];
[self.jugadorSlide addSubview:awesomeView];
awesomeView=nil;
}
[jugadorSlide setBackgroundColor:[UIColor blackColor]];
jugadorSlide.contentSize = CGSizeMake(68 * numberOfViews+240,78);
jugadorSlide.layer.cornerRadius = 11;
jugadorSlide.layer.masksToBounds = YES;
[jugadorSlide setContentOffset:CGPointMake(((68 * numberOfViews)/2), 0)];
//jugadorSlide.decelerationRate = UIScrollViewDecelerationRateNormal;
[self scrollViewDidEndDragging:jugadorSlide willDecelerate:NO];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
currentIndex = roundf(scrollView.contentOffset.x / 68);
NSLog(#"current end %d", currentIndex);
UIImageView *currentImage = [scrollView viewWithTag:currentIndex];
if (currentIndex>0&&currentIndex<=21){
if (currentIndex==currentImage.tag){
currentImage.alpha=1.0f;
[self changePerfilImage:currentImage.tag];}
CGPoint pointZero= CGPointMake(scrollView.contentOffset.x, currentImage.frame.origin.y);
[jugadorSlide setContentOffset:pointZero animated:YES];
}else {
UIImageView *currentImage = [scrollView viewWithTag:0];
NSLog(#"end dragging image tag %d", currentImage.tag);
currentImage.alpha=1.0f;
[self changePerfilImage:currentImage.tag];}
CGPoint pointZero= CGPointMake(currentImage.frame.origin.x+15, 0);
//[jugadorSlide setContentOffset:pointZero animated:YES];
}
As you can see, in the scrollViewDidEndDragging: "else" , I forced the tag as a desesperate solution, but images doesn't get clear.
You are incrementing the tag twice...
awesomeView.tag = i++;
Should just be:
awesomeView.tag = i+1;
I use i+1 because I never use a tag of 0 since any subview that hasn't been assigned a tag will have a tag of 0.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
NSInteger currentIndex = roundf(scrollView.contentOffset.x / 68.0) + 1;
UIImageView *currentImage = [scrollView viewWithTag:currentIndex];
...
}
If this doesn't work you should NSLog the currentIndex each time you land on a new image and see what is happening when you land on the first one.

Having problems with CALayer

So I have a class that returns a CALayer that has an array of CALayers added as sublayers, but the problem is that it doesn't seem to be rendering any of them. I think I may just be missing something about how CALayers work as I'm not very familiar yet. Could someone please take a look at my code to see what I am doing wrong?
- (CALayer*)drawMap {
CALayer* theLayer = [CALayer layer];
for (int y = 0; y < [self.height intValue]; y++) {
for (int x = 0; x < [self.width intValue]; x++) {
CALayer* tileLayer = [CALayer layer];
tileLayer.bounds = CGRectMake((x * [self.tileWidth intValue]), (y * [self.tileHeight intValue]), [self.tileWidth intValue], [self.tileHeight intValue]);
[tileLayer setBackgroundColor:[UIColor colorWithHue:(CGFloat)x saturation:(CGFloat)y brightness:255 alpha:1.0].CGColor];
[theLayer addSublayer:tileLayer];
}
}
[theLayer setBounds:CGRectMake([self.width intValue] * [self.tileWidth intValue], [self.height intValue] * [self.tileHeight intValue], 10, 10)];
return theLayer;
}
This is the code that initializes and draws the map.
Map* myMap = [[Map alloc] initFromFile];
[myMap setWidth:[NSNumber numberWithInt:100]];
[myMap setHeight:[NSNumber numberWithInt:100]];
[self.view.layer insertSublayer:[myMap drawMap] above:self.view.layer];
I can provide the headers if needed, but I don't think the problem is there and I don't want a huge post.
I think the problem is the bounds you're setting to your parent layer:
[theLayer setBounds:
CGRectMake(
[self.width intValue] * [self.tileWidth intValue],
[self.height intValue] * [self.tileHeight intValue],
10, 10)];
That would appear to set the bounds so that it starts just exactly past all the sublayers you've just added and extends for 10 points in both directions. I think the following would be more appropriate:
[theLayer setBounds:
CGRectMake(
0,
0,
[self.width intValue] * [self.tileWidth intValue],
[self.height intValue] * [self.tileHeight intValue])];
The following also looks fishy:
[self.view.layer insertSublayer:[myMap drawMap] above:self.view.layer];
[myMap drawMap] will become a sublayer of self.view.layer. self.view.layer is not one of its own subviews so it won't know what to do with that above: instruction. You probably want just addSublayer:.
Finally, this:
tileLayer.bounds = CGRectMake((x * [self.tileWidth intValue]), (y * [self.tileHeight intValue]), [self.tileWidth intValue], [self.tileHeight intValue]);
gives every single one of your sublayers exactly the same frame. Much like UIViews, the bounds are the source area for information and the frame is where that information will be put within the super layer. I think probably you want to set frame.
Finally, UIColor +colorWithHue:... clamps hue and saturation to the range [0, 1] so you probably want (CGFloat)x / [self.width floatValue] and the equivalent for saturation to ensure all your tiles come out in different colours.
EDIT: so, tying all that together, I modified your code slightly so that I didn't have to write the full encompassing class and added it to the Xcode view-based project template as follows:
#define kTileWidth 3
#define kTileHeight 3
#define kWidth 100
#define kHeight 100
- (CALayer*)drawMap {
CALayer* theLayer = [CALayer layer];
for (int y = 0; y < kHeight; y++)
{
for (int x = 0; x < kWidth; x++)
{
CALayer* tileLayer = [CALayer layer];
tileLayer.frame = CGRectMake((x * kTileWidth), (y * kTileHeight), kTileWidth, kTileHeight);
[tileLayer setBackgroundColor:[UIColor colorWithHue:(CGFloat)x/kWidth saturation:(CGFloat)y/kHeight brightness:255 alpha:1.0].CGColor];
[theLayer addSublayer:tileLayer];
}
}
[theLayer setFrame:CGRectMake(0, 0, kWidth * kTileWidth, kHeight * kTileHeight)];
return theLayer;
}
// ...
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view.layer addSublayer:[self drawMap]];
}
That gives the hue/saturation plane familiar from many an art package.