how to efficiently find a rect # some x,y point with iphone sdk - iphone

I am looking for an efficient way to handle the image/frame detection from touch methods. Let's say i am building a keyboard or similar to this. I have 'n' number of images placed on the UI. When someone touches an alphabet (which is an image), i can do the following to detect the corresponding letter
1) CGRectIntersectsRect(..,..) : if i use this, then i need to check each & every letter to find out what letter exists at that touch point (let's say 100,100). This becomes O(n). If i move my finger accross the screen, then i will get m points & all corresponding image detection becomes O(n*m) which is not good.
2) Other way is building a hash for each & every x,y position so that the look up will be simply O(1). But again this will be a memory constraint as i need to store 300*300 ( assuming i am using 300*300 screen size). if i reshuffle my letters, then everything needs to calculated again. So this is not good
In other words, i need some thing like , given a point (x,y), i need some way of finding which rectangle is covering that point efficiently.
Sorry for long post & any help would be grateful.
Thanks

If there are in a regular grid, then integer division by the grid size. Assuming you've a small, fixed screen size, a bucket array gives as similar gain ( a 2D grid, where each entry is a list of the rectangles which intersect that part of the grid ) is very fast if tuned correctly so the lists only have a few members. For unbounded or large spaces, KD trees can be used.

It's useful to have the rects you want as final targets set up as subviews as a larger UIView (or subclass) where you expect all these related hits to occur. For example, if you're building your own keyboard, you could add a bunch of UIButton objects as subviews and hit test those.
So, the easy and traditional way of hit testing a bunch of subviews is to simply have code triggered by someone hitting those buttons. For example, you could add the subviews as UIControl objects (which is a subclass of UIView that adds some useful methods for catching user touch events), and call addTarget:action:forControlEvents: to specify some method to be triggered when the user does something in the rect of that UIControl. For example, you can catch things like UIControlEventTouchDown or UIControlEventTouchDragEnter. You can read the complete list in the UIControl class reference.
Now, it sounds like you might be going for something even more customized. If you really want to start with a random (x,y) coordinate and know which rect it's in, you can also use the hitTest:withEvent: method of UIView. This method takes a point in a view, and finds the most detailed (lowest in the hierarchy) subview which contains that point.
If you want to use these subviews purely for hit testing and not for displaying, then you can set their background color to [UIColor clearColor], but don't hide them (i.e. set the hidden property to YES), disable user interaction with them (via the userInteractionEnabled BOOL property), or set the alpha below 0.1, since any of those things will cause the hitTest:withEvent: method to skip over that subview. But you can still use an invisible subview with this method call, as long as it meets these criteria.

Look at UIView's tag property. If your images are in UIViews or subviews of UIView, then you can set each tag and use the tag to look up in an array.
If not, then you can improve the speed by dividing your array of rectangles into sets that fit into larger rectangles. Test the outer rectangles first, then the inner rectangles. 25 rectangles would need only 10 tests worst case as 5 sets of 5.

Thanks Pete Kirkham & Tyler for your answers which are really helpful. Lets say i dont wanna use buttons as i am mainly displaying images as a small rectangles. To check for the rect # (x,y) , i can trigger that easily by making my grid as a square & finding
gridcolumn = Math.floor(pos.x / cellwidth); gridrow = Math.floor(pos.y / cellheight);
But my problem is with touchesMoved. Lets say i started # grid-1 & dragged till grid-9 (in a 3*3 matrix), in this case, i am assuming i will get 100-300 (x,y) positions, so everytime i need to run above formula to determine corresponding grid. This results in 300 calculations which might effect the performance.
So when i display an image as a rect, can i associate some id for that image? so that i can simply just save the ids in a list (from grid-1 to grid-9) so that i can avoid the above calculation.
Thanks for your help

Related

How would you create a ring of cells in flutter?

I would like to create a widget (I know it must be a CustomPainter) to draw something like this:
Notice that there are n concentric cell circles.
The main problem is that I need to access/paint each of this cells when needed to repaint it in different colors. I have been checking the CustomPainter canvas class and the only thing that could fit my needs is the draw arc thing. But, I can't provide a width for the arc (I tought I could draw a draw for every cell).
My last resort is using an image/sprite that would represent a cell. This way I could duplicate and transform it along a circle path to obtain something like the image. But I don't like the idea.
Has anybody accomplished this before in flutter?

Resizing image generated by PaintCode app

I have imported a vector image to PaintCode app and then export its Swift to code. I want to use this vector image in a small View (30x30) but since I want it to work on different devices, I need it to be size-independent.
The original size of the vector image is 512x512. When I add its class to a UIView, only a very small part of the vector image can be seen:
I need to somehow resize the image that can be fit in any size of a frame. I read somewhere, that I have to draw a frame in PaintCode app around the image, I did it but nothing changed.
Start by selecting the "Frame" option from the toolbar
Apply the frame to you canvas...
nb: If you mess up the frame DELETE IT and start again, modifying the frame can change the underlying vector, which is annoying
Apply the desired resize options. This can be confusing the first time.
I group all the elements into a single group. Select the group and on the "box" next to the coordinates of the group, change all the lines to "wiggly" lines. This allows paint code the greatest amount of flexibility when resizing the image...
Finally, change the export options. I tend to use both "Drawing" and "Image" as it provides me the greatest amount of flexibility during development
You should also look at Resizing Constraints, Resizing Drawing Methods and PaintCode Power User: Frames for more details

How can i set timer for wheel rotation in cylinder for iCarousel

I am using iCarousel in my project. So is there a way i can set timer , while i scroll the Cylinder wheel. I need to keep the wheel rotated for 5 seconds.Need the scrolling animation until that.
Well if you read the documentation of The iCarousel carefully you will find that there are certain methods which include the time duration it takes for the iCarousel to move from one index to the other, namely -
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)scrollDuration;
This method allows you to control how long the carousel takes to scroll to the specified index.
- (void)scrollByNumberOfItems:(NSInteger)itemCount duration:(NSTimeInterval)duration;
This method allows you to scroll the carousel by a fixed distance, measured in carousel item widths. Positive or negative values may be specified for itemCount, depending on the direction you wish to scroll. iCarousel gracefully handles bounds issues, so if you specify a distance greater than the number of items in the carousel, scrolling will either be clamped when it reaches the end of the carousel (if wrapping is disabled) or wrap around seamlessly.
- (void)scrollToOffset:(CGFloat)offset duration:(NSTimeInterval)duration;
This works the same way as scrollToItemAtIndex:, but allows you to scroll to a fractional offset. This may be useful if you wish to achieve a very precise animation effect. Note that if the scrollToItemBoundary property is set to YES, the carousel will automatically scroll to the nearest item index after you call this method. anyway.
- (void)scrollByOffset:(CGFloat)offset duration:(NSTimeInterval)duration;
This works the same way as scrollByNumberOfItems:, but allows you to scroll by a fractional number of items. This may be useful if you wish to achieve a very precise animation effect. Note that if the scrollToItemBoundary property is set to YES, the carousel will automatically scroll to the nearest item index after you call this method anyway.
Please check these methods . Hope they help...

How to Create Customized Time Bar in iPhone?

I need to create a time bar like the image attached.The blue lines are the dates indicating some actions.The big Red Arrow mark is used to slide for selecting any of the blue line. At background the bar is divided into years.The small red circles are to indicate the years.
Any idea ,how do i start?
Thanks
If the blue bars don't move a lot, and you don't need to resize this view very often (which is usually the case on an iPhone), then I'd recommend subclassing UIControl (or UIView) and implement it yourself.
Have an NSArray property storing NSDate objects and methods like addDate:, removeDate:, removeDateAtIndex: to change it's content from an other object (like your view controller). In these methods you add or remove the passed date and call [self setNeedsDisplay]; to redraw the lines.
You will need a few methods to calculate the position (in pixels) of a date on the slider and to calculate the date at a specific coordinate. This should be easy to to (basic linear interpolation).
And assuming that the red slider is only able to point to blue lines (but not between them) add a NSDate pointer variable to the currently selected date. In the
In the drawRect: method, you need to draw all the lines using CoreGraphics functions. Look up the documentation if you need help with this. Apple has some great sample apps too.
To show the red slider, you could either add a custom UIImageView, with a UIPanGestureRecognizer and make sure it only moves vertically in the gesture handler. Or it might be possible to add a UISlider without track images (I'm not 100% sure about that). In either case, you need to adjust the slider's position once the user let's go and make it jump to the nearest blue line.
A rough idea,
1. Get the length of the entire TimeBar.Let it be t.
2. Divide by x=numberofYears*365.let it be t_eachday_pos=t/x
3. get the position of each day,calculate its offset as daycount*t_eachday_pos;
4. Add your blueLine as a customButton.
5. To do some action, pass the x daynumber(eg. day 245 of year 2 etc.)
Try this, I have used the same thing in one of my app, and it is working

iPhone: How to Determine Average Light/Dark of an Area of an UIImage

I need to place labels with a transparent background over a variable-content UIImage. Readability will vary significantly depending on the relationship between the color of the label's text and the color/luminosity of the area of the image displayed under the label. Since the image will be constantly changing, the color of the label's text needs to change in sync.
I have found several techniques for determining the color, perceived luminosity etc of a single pixel. However, I need to rather quickly (while a view loads) determine the rough perceived color/luminosity of an area of the UIImage under the frame of the UILabel. I presume I will also need to measure the alpha because the same color/luminosity looks different at different alpha values.
Is there a way to calculate such a value for an area? Will I be reduced to simply summing pixels? If it comes to that, is there an algorithm to accomplish this?
I've thought of two possible approaches:
Perform some "folding" operations i.e. combining pixels from one half of the area to the other half. Then repeat until I get a single value. Would this be practical? How would you logically combine pixels to average their perceived color/luminosity?
Sample a statistically significant number of pixels in the area and then combine them (somehow) to get a rough measure.
I think this problem comes up a lot these days with people being so found of customizing backgrounds. Seems like something that would be worth my time to bang out a category or class to handle this and then share it around.
What about simply outlining your text in a way that it will show on both dark and light backgrounds?
This is how it is handled in other situations where text must be displayed over a background with unknown content (for example, films with subtitles).