Search Results

Search found 64 results on 3 pages for 'cgcontext'.

Page 3/3 | < Previous Page | 1 2 3 

  • iPhone: Going from transformed layers to jpeg

    - by Devin Ross
    I have a bunch of images that are transformed (using touch gestures). I want to take the transformations the user does to the images and create a jpeg from it. (ie. if a user rotates a photo to the right, I want to get a jpeg of the photo rotate to the right just as the looks on screen). This takes into account that the photo could be bigger than whats displayed on screen too (no screenshots). I'm trying to use CGContext (CGContextRotateCTM specifically) but its not been too successful. Thanks for the help.

    Read the article

  • iOS - pass UIImage to shader as texture

    - by martin pilch
    I am trying to pass UIImage to GLSL shader. The fragment shader is: varying highp vec2 textureCoordinate; uniform sampler2D inputImageTexture; uniform sampler2D inputImageTexture2; void main() { highp vec4 color = texture2D(inputImageTexture, textureCoordinate); highp vec4 color2 = texture2D(inputImageTexture2, textureCoordinate); gl_FragColor = color * color2; } What I want to do is send images from camera and do multiply blend with texture. When I just send data from camera, everything is fine. So problem should be with sending another texture to shader. I am doing it this way: - (void)setTexture:(UIImage*)image forUniform:(NSString*)uniform { CGSize sizeOfImage = [image size]; CGFloat scaleOfImage = [image scale]; CGSize pixelSizeOfImage = CGSizeMake(scaleOfImage * sizeOfImage.width, scaleOfImage * sizeOfImage.height); //create context GLubyte * spriteData = (GLubyte *)malloc(pixelSizeOfImage.width * pixelSizeOfImage.height * 4 * sizeof(GLubyte)); CGContextRef spriteContext = CGBitmapContextCreate(spriteData, pixelSizeOfImage.width, pixelSizeOfImage.height, 8, pixelSizeOfImage.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast); //draw image into context CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, pixelSizeOfImage.width, pixelSizeOfImage.height), image.CGImage); //get uniform of texture GLuint uniformIndex = glGetUniformLocation(__programPointer, [uniform UTF8String]); //generate texture GLuint textureIndex; glGenTextures(1, &textureIndex); glBindTexture(GL_TEXTURE_2D, textureIndex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //create texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixelSizeOfImage.width, pixelSizeOfImage.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureIndex); //"send" to shader glUniform1i(uniformIndex, 1); free(spriteData); CGContextRelease(spriteContext); } Uniform for texture is fine, glGetUniformLocation function do not returns -1. The texture is PNG file of resolution 2000x2000 pixels. PROBLEM: When the texture is passed to shader, I have got "black screen". Maybe problem are parameters of the CGContext or parameters of the function glTexImage2D Thank you

    Read the article

  • How i implement the CGContextBeginPath() functions in iphone using objective-C?

    - by Rajendra Bhole
    Hi, I want to divide the circle using CGContext and following code of function given by apple API reference library, CGContextBeginPath (context); for (k = 0; k < count; k += 2) { CGContextMoveToPoint(context, s[k].x, s[k].y); CGContextAddLineToPoint(context, s[k+1].x, s[k+1].y); } CGContextStrokePath(context); The above code i want to implement inside following code instead of C5, C6 and C7 block, (void)drawRect:(CGRect)rect { // circle CGContextRef contextRef = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(contextRef, 0, 0, 255, 0.1); CGContextSetRGBStrokeColor(contextRef, 0, 0, 255, 0.5); //CGContextFillEllipseInRect(contextRef, CGRectMake(100, 100, 150, 150)); CGContextStrokeEllipseInRect(contextRef, CGRectMake(100, 100, 150, 150)); CGContextRef c5= UIGraphicsGetCurrentContext(); CGContextSetLineWidth(c5, 2.0); CGContextSetStrokeColorWithColor(c5, [UIColor brownColor].CGColor); CGContextBeginPath(c5); CGContextMoveToPoint(c5, 175.0f, 175.0f); CGContextAddLineToPoint(c5, 100.0f, 175.0f); CGContextStrokePath(c5); CGContextRef c6= UIGraphicsGetCurrentContext(); CGContextSetLineWidth(c6, 2.0); CGContextSetStrokeColorWithColor(c6, [UIColor blueColor].CGColor); CGContextBeginPath(c6); CGContextMoveToPoint(c6, 175.0f, 175.0f); CGContextAddLineToPoint(c6, 175.0f, 250.0f); CGContextStrokePath(c6); CGContextRef c7= UIGraphicsGetCurrentContext(); CGContextSetLineWidth(c7, 02.0); CGContextSetStrokeColorWithColor(c7, [UIColor greenColor].CGColor); CGContextBeginPath(c7); CGContextMoveToPoint(c7, 175.0f, 175.0f); CGContextAddLineToPoint(c7, 175.0f, 100.0f); CGContextStrokePath(c7); } It is possible, if it is then how i should have implement?

    Read the article

  • How to write text(using CGContextShowTextAtPoint) dynamically near graph x and y-axis intervals?

    - by Rajendra Bhole
    I developed graph using NSObject class and using CGContext method. The following code displaying dynamically in X and Y-axis intervals, CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextSetLineWidth(ctx, 2.0); CGContextMoveToPoint(ctx, 30.0, 200.0); CGContextAddLineToPoint(ctx, 30.0, 440.0); for(float y = 400.0; y >= 200.0; y-=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, 28, y); CGContextAddLineToPoint(ctx, 32, y); CGContextStrokePath(ctx); //CGContextClosePath(ctx); } CGContextMoveToPoint(ctx, 10, 420.0); CGContextAddLineToPoint(ctx, 320, 420.0); //CGContextAddLineToPoint(ctx, 320.0, 420.0); //CGContextStrokePath(ctx); for(float x = 60.0; x <= 260.0; x+=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, x, 418.0); CGContextAddLineToPoint(ctx, x, 422.0); CGContextStrokePath(ctx); CGContextClosePath(ctx); } I want to write the dynamic text on the X and Y-axis lines near the intervals (like X-axis is denoting number of days per week and Y-axis denoting something per someting)? Thanks.

    Read the article

  • How to write text(using CGContextShowTextAtPoint) on graph x and y-axis intervals points?

    - by Rajendra Bhole
    I developed graph using NSObject class and using CGContext method. The following code displaying dynamically in X and Y-axis intervals, CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextSetLineWidth(ctx, 2.0); CGContextMoveToPoint(ctx, 30.0, 200.0); CGContextAddLineToPoint(ctx, 30.0, 440.0); for(float y = 400.0; y >= 200.0; y-=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, 28, y); CGContextAddLineToPoint(ctx, 32, y); CGContextStrokePath(ctx); //CGContextClosePath(ctx); } CGContextMoveToPoint(ctx, 10, 420.0); CGContextAddLineToPoint(ctx, 320, 420.0); //CGContextAddLineToPoint(ctx, 320.0, 420.0); //CGContextStrokePath(ctx); for(float x = 60.0; x <= 260.0; x+=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, x, 418.0); CGContextAddLineToPoint(ctx, x, 422.0); CGContextStrokePath(ctx); CGContextClosePath(ctx); } I want to write the dynamic text on the X and Y-axis lines near the intervals (like X-axis is denoting number of days per week and Y-axis denoting something per someting)? Thanks.

    Read the article

  • Unexplained crashs with coregraphic

    - by Ziggy
    Hello there, i'm on this bug for a week now, and i can't solve it. I have some crash with coregraphic calls, it happen randomly (sometimes after 2 mn, or just at the start), but often at the same places in the code. I have a class that just wrap a CGContext, it have a CGContextRef as member. This Object is re-created each time DrawRect() is called, so the CGContextRef is always up-to-date. The draw calls came from the main thread, only After looking for this kind of error, it appear that it should be object Release related. Here is an example of an error : #0 0x90d8a7a7 in ___forwarding___ #1 0x90d8a8b2 in __forwarding_prep_0___ #2 0x90d0d0b6 in CFRetain #3 0x95e54a5d in CGColorRetain #4 0x95e5491d in CGGStateCreateCopy #5 0x95e5486d in CGGStackSave #6 0x95e54846 in CGContextSaveGState #7 0x00073500 in CAutoContextState::CAutoContextState at Context.cpp:47 the AutoContextSave() class look like this : class CAutoContextState { private: CGContextRef m_Hdc; public: CAutoContextState(const CGContextRef& Hdc) { m_Hdc = Hdc; CGContextSaveGState(m_Hdc); } virtual ~CAutoContextState() { CGContextRestoreGState(m_Hdc); } }; It crash at CGContextSaveGState(m_Hdc). Here is what i see into GDB: * -[Not A Type retain]: message sent to deallocated instance 0x16a148b0. When i type malloc-history on the address, i have this : 0: 0x954cf10c in malloc_zone_malloc 1: 0x90d0d201 in _CFRuntimeCreateInstance 2: 0x95e3fe88 in CGTypeCreateInstanceWithAllocator 3: 0x95e44297 in CGTypeCreateInstance 4: 0x95e58f57 in CGColorCreate 5: 0x71fdd in _ZN4Flux4Draw8CContext10DrawStringERKNS_7CStringEPKNS0_5CFontEPKNS0_6CBrushERKNS_5CRectENS0_12tagAlignmentESE_NS0_17tagStringTrimmingEfiPKf at /Volumes/Sources Mac/Flux/Sources/DotFlux/Projects/../Draw/CoreGraphic/Context.cpp:1029 Which point me at this line of code : f32 components[] = {pSolidBrush->GetColor().GetfRed(), pSolidBrush->GetColor().GetfGreen(), pSolidBrush->GetColor().GetfBlue(), pSolidBrush->GetColor().GetfAlpha()}; //{ 1.0, 0.0, 0.0, 0.8 }; CGColorRef TextColor = CGColorCreate(rgbColorSpace, components); Point this func : CGColorCreate(); Any help would be appreciated, i need to finish this task very soon, but i don't know how to resolve this :( Thanks.

    Read the article

  • Presenting an image cropping interface

    - by wkw
    I'm trying to engineer a UI for cropping images in iphone OS and suspect I'm going about things the hard way. My goal is pretty much what the Tapbots duo have done with Pastebot. In that app, they dim the source image but provide a movable and resizable cropping view and the image you're cropping is in a zoomable scrollview; when you resize or move the underlying image, the cropping view adjusts appropriately. I mocked up a composite image which will give a sense of the design I'm after, along with how I presently have my view hierarchy setup, viewable here The approach I've started with is the following: UIImageView with the image to crop is in a scrollview, a plain UIView with black fill and suitable transparency/alpha setting is added in front of the imageview. I then use a custom UIView which is a sibling to the scrollview at a higher level, which implements the drawRect: method and for the most part calls CGImageCreateWithImageInRect to get the portion of the image's bitmap that matches the position of the cropping view and draws that to the CGContext. in the viewcontroller I'm using the UIScrollViewDelegate methods to track scrolling and passing those changes to the custom cropping UIView so it stays in sync with the scroll contentOffset. That much is finally working. But trying to keep in sync as the scrollview zoomScale changes is when I figured I should ask for help. Looking for suggestions or guidance. My initial approach just seems like more work than is required. Could this be done with a masking layer in the ImageView? And if so, how would I setup the tracking for moving and resizing the cropping rect? My experience working with layers is non-nil, but very limited thus far.

    Read the article

  • The best way to implement drawing features like Keynote

    - by Shamseddine
    Hi all, I'm trying to make a little iPad tool's for drawing simple geometrical objects (rect, rounded rect, ellipse, star, ...). My goal is to make something very close to Keynote (drawing feature), i.e. let the user add a rect (for instance), resizing it and moving it. I want too the user can select many objects and move them together. I've thought about at least 3 differents ways to do that : Extends UIView for each object type, a class for Rect, another for Ellipse, ... With custom drawing method. Then add this view as subview of the global view. Extends CALayer for each object type, a class for Rect, another for Ellipse, ... With custom drawing method. Then add this layer as sublayer of the global view layer's. Extends NSObject for each object type, a class for Rect, another for Ellipse, ... With just a drawing method which will get as argument a CGContext and a Rect and draw directly the form in it. Those methods will be called by the drawing method of the global view. I'm aware that the two first ways come with functions to detect touch on each object, to add easily shadows,... but I'm afraid that they are a little too heavy ? That's why I thought about the last way, which it seems to be straight forward. Which way will be the more efficient ??? Or maybe I didn't thought another way ? Any help will be appreciated ;-) Thanks.

    Read the article

  • Rendering a CGPDFPage into a UIImage

    - by James Antrobus
    I'm trying to render a CGPDFPage (selected from a CGPDFDocument) into a UIImage to display on a view. I have the following code in MonoTouch which gets me part way there. RectangleF PDFRectangle = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height); public override void ViewDidLoad () { UIGraphics.BeginImageContext(new SizeF(PDFRectangle.Width, PDFRectangle.Height)); CGContext context = UIGraphics.GetCurrentContext(); context.SaveState(); CGPDFDocument pdfDoc = CGPDFDocument.FromFile("test.pdf"); CGPDFPage pdfPage = pdfDoc.GetPage(1); context.DrawPDFPage(pdfPage); UIImage testImage = UIGraphics.GetImageFromCurrentImageContext(); pdfDoc.Dispose(); context.RestoreState(); UIImageView imageView = new UIImageView(testImage); UIGraphics.EndImageContext(); View.AddSubview(imageView); } A section of the CGPDFPage is displayed but rotated back-to-front and upside down. My question is, how do I select the full pdf page and flip it round to display correctly. I have seen a few examples using ScaleCTM and TranslateCTM but couldn't seem to get them working. Any examples in ObjectiveC are fine, I'll take all the help I can get :) Thanks

    Read the article

  • Very simple test view in MonoTouch draws a line using Core Graphics but view content is not shown

    - by Krumelur
    Hi, I give up now on this very simple test I've been trying to run. I want to add a subview to my window which does nothing but draw a line from one corner of the iPhone's screen to the other and then, using touchesMoved() it is supposed to draw a line from the last to the current point. The issues: 1. Already the initial line is not visible. 2. When using Interface Builder, the initial line is visible, but drawRect() is never called, even if I call SetNeedsDisplay(). It can't be that hard...can somebody fix the code below to make it work? In main.cs in FinishedLaunching(): oView = new TestView(); oView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; oView.Frame = new System.Drawing.RectangleF(0, 0, 320, 480); window.AddSubview(oView); window.MakeKeyAndVisible (); The TestView.cs: using System; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using System.Drawing; using MonoTouch.CoreAnimation; using MonoTouch.Foundation; namespace Test { public class TestView : UIView { public TestView () : base() { } public override void DrawRect (RectangleF area, UIViewPrintFormatter formatter) { CGContext oContext = UIGraphics.GetCurrentContext(); oContext.SetStrokeColor(UIColor.Red.CGColor.Components); oContext.SetLineWidth(3.0f); this.oLastPoint.Y = UIScreen.MainScreen.ApplicationFrame.Size.Height - this.oLastPoint.Y; this.oCurrentPoint.Y = UIScreen.MainScreen.ApplicationFrame.Size.Height - this.oCurrentPoint.Y; oContext.StrokeLineSegments(new PointF[] {this.oLastPoint, this.oCurrentPoint }); oContext.Flush(); oContext.RestoreState(); Console.Out.WriteLine("Current X: {0}, Y: {1}", oCurrentPoint.X.ToString(), oCurrentPoint.Y.ToString()); Console.Out.WriteLine("Last X: {0}, Y: {1}", oLastPoint.X.ToString(), oLastPoint.Y.ToString()); } private PointF oCurrentPoint = new PointF(0, 0); private PointF oLastPoint = new PointF(320, 480); public override void TouchesMoved (MonoTouch.Foundation.NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); UITouch oTouch = (UITouch)touches.AnyObject; this.oCurrentPoint = oTouch.LocationInView(this); this.oLastPoint = oTouch.PreviousLocationInView(this); this.SetNeedsDisplay(); } } }

    Read the article

  • iPhone development: pointer being freed was not allocated

    - by w4nderlust
    Hello, i got this message from the debugger: Pixture(1257,0xa0610500) malloc: *** error for object 0x21a8000: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug so i did a bit of tracing and got: (gdb) shell malloc_history 1257 0x21a8000 ALLOC 0x2196a00-0x21a89ff [size=73728]: thread_a0610500 |start | main | UIApplicationMain | GSEventRun | GSEventRunModal | CFRunLoopRunInMode | CFRunLoopRunSpecific | __CFRunLoopDoObservers | CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) | CA::Transaction::commit() | CA::Context::commit_transaction(CA::Transaction*) | CALayerDisplayIfNeeded | -[CALayer _display] | CABackingStoreUpdate | backing_callback(CGContext*, void*) | -[CALayer drawInContext:] | -[UIView(CALayerDelegate) drawLayer:inContext:] | -[AvatarView drawRect:] | -[AvatarView overlayPNG:] | +[UIImageUtility createMaskOf:] | UIGraphicsGetImageFromCurrentImageContext | CGBitmapContextCreateImage | create_bitmap_data_provider | malloc | malloc_zone_malloc and i really can't understand what i am doing wrong. here's the code of the [UIImageUtility createMaskOf:] function: + (UIImage *)createMaskOf:(UIImage *)source { CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height); UIGraphicsBeginImageContext(CGSizeMake(source.size.width, source.size.height)); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0, source.size.height); CGContextScaleCTM(context, 1.0, -1.0); UIImage *original = [self createGrayCopy:source]; CGContextRef context2 = CGBitmapContextCreate(NULL, source.size.width, source.size.height, 8, 4 * source.size.width, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast); CGContextDrawImage(context2, CGRectMake(0, 0, source.size.width, source.size.height), original.CGImage); CGImageRef unmasked = CGBitmapContextCreateImage(context2); const float myMaskingColorsFrameColor[6] = { 1,256,1,256,1,256 }; CGImageRef mask = CGImageCreateWithMaskingColors(unmasked, myMaskingColorsFrameColor); CGContextSetRGBFillColor (context, 256,256,256, 1); CGContextFillRect(context, rect); CGContextDrawImage(context, rect, mask); UIImage *whiteMasked = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return whiteMasked; } the other custom function called before that is the following: - (UIImage *)overlayPNG:(SinglePart *)sp { NSLog([sp description]); // Rect and context setup CGRect rect = CGRectMake(0, 0, sp.image.size.width, sp.image.size.height); NSLog(@"%f x %f", sp.image.size.width, sp.image.size.height); // Create an image of a color filled rectangle UIImage *baseColor = nil; if (sp.hasOwnColor) { baseColor = [UIImageUtility imageWithRect:rect ofColor:sp.color]; } else { SinglePart *facePart = [editingAvatar.face.partList objectAtIndex:0]; baseColor = [UIImageUtility imageWithRect:rect ofColor:facePart.color]; } // Crete the mask of the layer UIImage *mask = [UIImageUtility createMaskOf:sp.image]; mask = [UIImageUtility createGrayCopy:mask]; // Create a new context for merging the overlay and a mask of the layer UIGraphicsBeginImageContext(CGSizeMake(sp.image.size.width, sp.image.size.height)); CGContextRef context2 = UIGraphicsGetCurrentContext(); // Adjust the coordinate system so that the origin // is in the lower left corner of the view and the // y axis points up CGContextTranslateCTM(context2, 0, sp.image.size.height); CGContextScaleCTM(context2, 1.0, -1.0); // Create masked overlay color layer CGImageRef MaskedImage = CGImageCreateWithMask (baseColor.CGImage, mask.CGImage); // Draw the base color layer CGContextDrawImage(context2, rect, MaskedImage); // Get the result of the masking UIImage* overlayMasked = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIGraphicsBeginImageContext(CGSizeMake(sp.image.size.width, sp.image.size.height)); CGContextRef context = UIGraphicsGetCurrentContext(); // Adjust the coordinate system so that the origin // is in the lower left corner of the view and the // y axis points up CGContextTranslateCTM(context, 0, sp.image.size.height); CGContextScaleCTM(context, 1.0, -1.0); // Get the result of the blending of the masked overlay and the base image CGContextDrawImage(context, rect, overlayMasked.CGImage); // Set the blend mode for the next drawn image CGContextSetBlendMode(context, kCGBlendModeOverlay); // Component image drawn CGContextDrawImage(context, rect, sp.image.CGImage); UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CGImageRelease(MaskedImage); return blendedImage; }

    Read the article

  • Help needed with drawRect:

    - by Andrew Coad
    Hi, I'm having a fundamental issue with use of drawRect: Any advice would be greatly appreciated. The application needs to draw a variety of .png images at different times, sometimes with animation, sometimes without. A design goal that I was hoping to adhere to is to have the code inside drawRect: very simple and "dumb" - i.e. just do drawing and no other application logic. To draw the image I am using the drawAtPoint: method of UIImage. Since this method does not take a CGContext as a parameter, it can only be called within the drawRect: method. So I have: - (void)drawRect:(CGRect)rect { [firstImage drawAtPoint:CGPointMake(firstOffsetX, firstOffsetY)]; } All fine and dandy for one image. To draw multiple images (over time) the approach I have taken is to maintain an array of dictionaries with each dictionary containing an image, the point location to draw at and a flag to enable/suppress drawing for that image. I add dictionaries to the array over time and trigger drawing via the setNeedsDisplay: method of UIView. Use of an array of dictionaries allows me to completely reconstruct the entire display at any time. drawRect: now becomes: - (void)drawRect:(CGRect)rect { for (NSMutableDictionary *imageDict in [self imageDisplayList]) { if ([[imageDict objectForKey:@"needsDisplay"] boolValue]) { [[imageDict objectForKey:@"image"] drawAtPoint:[[imageDict objectForKey:@"location"] CGPointValue]]; [imageDict setValue:[NSNumber numberWithBool:NO] forKey:@"needsDisplay"]; } } } Still OK. The code is simple and compact. Animating this is where I run into problems. The first problem is where do I put the animation code? Do I put it in UIView or UIViewController? If in UIView, do I put it in drawRect: or elsewhere? Because the actual animation depends on the overall state of the application, I would need nested switch statements which, if put in drawRect:, would look something like this: - (void)drawRect:(CGRect)rect { for (NSMutableDictionary *imageDict in [self imageDisplayList]) { if ([[imageDict objectForKey:@"needsDisplay"] boolValue]) { switch ([self currentState]) { case STATE_1: switch ([[imageDict objectForKey:@"animationID"] intValue]) { case ANIMATE_FADE_IN: [self setAlpha:0.0]; [UIView beginAnimations:[[imageDict objectForKey:@"animationID"] intValue] context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; [UIView setAnimationDuration:2]; [self setAlpha:1.0]; break; case ANIMATE_FADE_OUT: [self setAlpha:1.0]; [UIView beginAnimations:[[imageDict objectForKey:@"animationID"] intValue] context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationCurve:UIViewAnimationCurveEaseOut]; [UIView setAnimationDuration:2]; [self setAlpha:0.0]; break; case ANIMATE_OTHER: // similar code here break; default: break; } break; case STATE_2: // similar code here break; default: break; } [[imageDict objectForKey:@"image"] drawAtPoint:[[imageDict objectForKey:@"location"] CGPointValue]]; [imageDict setValue:[NSNumber numberWithBool:NO] forKey:@"needsDisplay"]; } } [UIView commitAnimations]; } In addition, to make multiple sequential animations work correctly, there would need to be an outer controlling mechanism involving the animation delegate animationDidStop: callback that would set the needsDisplay entries in the dictionaries to allow/suppress drawing (and animation). The point that we are at now is that it all starts to look very ugly. More specifically: drawRect: starts to bloat quickly and contain code that is not "just drawing" code the UIView needs implicit awareness of the application state the overall process of drawing is now spread across three methods at a minimum And on to the point of this post: how can I do this better? What would the experts out there recommend in terms of overall structure? How can I keep application state information out of the view? Am I looking at this problem from the wrong direction. Is there some completely different approach that I should consider?

    Read the article

  • Can draw on only half of UIView

    - by ydlee777
    Hello. I am trying to draw grid on a UIView on a UIScrollView. The width of UIView is about 1000 pixels. However, I can draw lines only about first 340 pixels of the UIView. Can anyone help me on this? The drawGrid function is - (void)drawRect:(CGRect)rect { NSInteger width = 25 * 5 * 10; NSInteger height = (10 * 2 + 10) * 12; NSInteger i; //Get the CGContext from this view CGContextRef context = UIGraphicsGetCurrentContext(); // Draw rectangle with a blue stroke color and white fill color CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0); CGContextSetLineWidth(context, 2.0); CGContextAddRect(context, CGRectMake(0.0, 0.0, width, height)); CGContextFillPath(context); // Draw grid with red color CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); // Set the width of the pen mark CGContextSetLineWidth(context, 0.2); for (i = 0; i < height; i += 5) { if (i % 25 == 0) { CGContextSetLineWidth(context, 0.4); // Draw a line CGContextMoveToPoint(context, i, 0.0); CGContextAddLineToPoint(context, i, width); CGContextStrokePath(context); CGContextSetLineWidth(context, 0.2); } else { // Draw a line CGContextMoveToPoint(context, i, 0.0); CGContextAddLineToPoint(context, i, width); CGContextStrokePath(context); } } for (i = 0; i < width; i += 5) { if (i % 25 == 0) { CGContextSetLineWidth(context, 0.4); // Draw a line CGContextMoveToPoint(context, 0.0, i); CGContextAddLineToPoint(context, height, i); CGContextStrokePath(context); CGContextSetLineWidth(context, 0.2); } else { // Draw a line CGContextMoveToPoint(context, 0.0, i); CGContextAddLineToPoint(context, height, i); CGContextStrokePath(context); } } } I am also setting up the UIScrollView and UIView as follows: - (void)viewDidLoad { [super viewDidLoad]; CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); waveScrollView = [[WaveScrollView alloc] initWithFrame:frame]; CGRect waveframe = CGRectMake(0, 0, 25 * 5 * 10, (10 * 2 + 10) * 12); EKGWaveView *ekgWaveView = [[EKGWaveView alloc] initWithFrame:waveframe]; waveScrollView.contentSize = CGSizeMake(waveframe.size.width, waveframe.size.height); waveScrollView.maximumZoomScale = 4.0; waveScrollView.minimumZoomScale = 0.75; waveScrollView.clipsToBounds = YES; waveScrollView.aView = ekgWaveView; [waveScrollView addSubview:ekgWaveView]; waveScrollView.delegate = self; [self.view addSubview:waveScrollView]; } I appreciate any help. Thanks.

    Read the article

  • Instruments memory leak iphone

    - by dubbeat
    Hi, I posted this problem a few days ago but it was very muddled and my question wasnt very clear so I removed it. I've been digging around and the memory leak is still persiting. Hopefully this attempt will be clearer. First off I've run the static analyzer and it reports no memory leaks. I then ran Instruments and it pointed to a memory leak at this line of code. As far as I can see there is no memory leak. featured=[[UILabel alloc]initWithFrame:CGRectMake(130,15, 200, 15)]; //[featured setFont:[UIFont UIFontboldSystemFontOfSize:20]]; featured.font = [UIFont boldSystemFontOfSize:20]; featured.backgroundColor= [UIColor clearColor]; featured.textColor=[UIColor blackColor]; featured.text= @"Featured Promo"; [self.view addSubview:featured]; [featured release]; featured=nil; If I comment out the above code Instruments reports another memory leak in another block of code where there is no discernible leak. UIButton *populartbutton = [[UIButton buttonWithType:UIButtonTypeRoundedRect]]; populartbutton.frame = CGRectMake(112, 145, 90, 22); // size and position of button [populartbutton setTitle:@"Popular" forState:UIControlStateNormal]; populartbutton.backgroundColor = [UIColor clearColor]; populartbutton.adjustsImageWhenHighlighted = YES; [populartbutton addTarget:self action:@selector(getpopular:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:populartbutton]; Instruments also says Responsible Library = Core Graphics Responsible Frame = open_handle_to_dylib_path This Is the stack trace. 53 Promo start 52 Promo main /Users/..2/main.m:14 51 UIKit UIApplicationMain 50 UIKit -[UIApplication _run] 49 CoreFoundation CFRunLoopRunInMode 48 CoreFoundation CFRunLoopRunSpecific 47 GraphicsServices PurpleEventCallback 46 UIKit _UIApplicationHandleEvent 45 UIKit -[UIApplication sendEvent:] 44 UIKit -[UIApplication handleEvent:withNewEvent:] 43 UIKit -[UIApplication _reportAppLaunchFinished] 42 QuartzCore CA::Transaction::commit() 41 QuartzCore CA::Context::commit_transaction(CA::Transaction*) 40 QuartzCore CALayerLayoutIfNeeded 39 QuartzCore -[CALayer layoutSublayers] 38 UIKit -[UILayoutContainerView layoutSubviews] 37 UIKit -[UINavigationController _startDeferredTransitionIfNeeded] 36 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:] 35 UIKit -[UINavigationController _layoutViewController:] 34 UIKit -[UINavigationController_computeAndApplyScrollContentInsetDeltaForViewController:] 33 UIKit -[UIViewController contentScrollView] 32 UIKit -[UIViewController view] 31 Promo -[FeaturedLevelViewController viewDidLoad] /Users/..s/FeaturedLevelViewController.m:67 // THIS IS MY CLASS WHERE THE CODE SAMPLES ABOVE ARE FROM 30 UIKit -[UILabel initWithFrame:] 29 UIKit -[UILabel _commonInit] 28 UIKit +[UILabel defaultFont] 27 UIKit +[UIFont systemFontOfSize:] 26 GraphicsServices GSFontCreateWithName 25 CoreGraphics CGFontCreateWithName 24 CoreGraphics CGFontCreateWithFontName 23 CoreGraphics CGFontFinderGetDefault 22 CoreGraphics CGFontGetVTable 21 libSystem.B.dylib pthread_once 20 CoreGraphics load_vtable 19 CoreGraphics load_library 18 CoreGraphics CGLibraryLoadFunction 17 CoreGraphics load_function 16 CoreGraphics open_handle_to_dylib_path 15 libSystem.B.dylib dlopen 14 dyld dlopen 13 dyld dyld::link(ImageLoader*, bool, ImageLoader::RPathChain const&) 12 dyld ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, ImageLoader::RPathChain const&) 11 dyld ImageLoader::recursiveLoadLibraries(ImageLoader::LinkContext const&, bool, ImageLoader::RPathChain const&) 10 dyld dyld::libraryLocator(char const*, bool, char const*, ImageLoader::RPathChain const*) 9 dyld dyld::load(char const*, dyld::LoadContext const&) 8 dyld dyld::loadPhase0(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*) 7 dyld dyld::loadPhase1(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*) 6 dyld dyld::loadPhase3(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*) 5 dyld dyld::loadPhase4(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*) 4 dyld dyld::loadPhase5(char const*, dyld::LoadContext const&, std::vector<char const*, std::allocator<char const*> >*) 3 dyld dyld::mkstringf(char const*, ...) 2 dyld strdup 1 dyld malloc 0 libSystem.B.dylib malloc I'm really not too sure how to use this information to fix the problem so any guidance would be appreciated. Perhaps the answer is in the trace but I just don't know what to look for? EDIT:: The above stack trace is when running on the simulator. The following is from running on a device. This trace does not point to any of my own classes 23 Promo 0x0 22 libSystem.B.dylib _pthread_body 21 Foundation __NSThread__main__ 20 Foundation +[NSThread exit] 19 libSystem.B.dylib _pthread_exit 18 libSystem.B.dylib _pthread_tsd_cleanup 17 QuartzCore CA::Transaction::release_thread(void*) 16 QuartzCore CA::Transaction::commit() 15 QuartzCore CA::Context::commit_transaction(CA::Transaction*) 14 QuartzCore CALayerDisplayIfNeeded 13 QuartzCore -[CALayer display] 12 QuartzCore -[CALayer _display] 11 QuartzCore CABackingStoreUpdate 10 QuartzCore backing_callback(CGContext*, void*) 9 QuartzCore -[CALayer drawInContext:] 8 UIKit -[UIView(CALayerDelegate) drawLayer:inContext:] 7 UIKit -[UILabel drawRect:] 6 UIKit -[UILabel drawTextInRect:] 5 UIKit -[UILabel _drawTextInRect:baselineCalculationOnly:] 4 UIKit -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:] 3 UIKit -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:includeEmoji:] 2 WebCore WKSetCurrentGraphicsContext 1 WebCore CurrentThreadContext() 0 libSystem.B.dylib calloc

    Read the article

< Previous Page | 1 2 3