Color Picker for iOS

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    // Do any additional setup after loading the view, typically from a nib.
   
    if (self.cPicker == nil) {
        [self.view setBackgroundColor:[UIColor grayColor]];
        self.cPicker = [[VBColorPicker alloc] initWithFrame:CGRectMake(0, 0, 202, 202)];
        [_cPicker setCenter:self.view.center];
        [self.view addSubview:_cPicker];
        [_cPicker setDelegate:self];
        [_cPicker showPicker];
       
        // set default YES!
        [_cPicker setHideAfterSelection:NO];
    }
     
}

// set color from picker
- (void) pickedColor:(UIColor *)color {
    [_rect setBackgroundColor:color];
    [_cPicker hidePicker];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![_cPicker isHidden]) {
        [_cPicker hidePicker];
    }
}

// show picker by double touch
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
   
    if (touch.tapCount == 2) {
        [_cPicker setCenter:[touch locationInView:self.view]];
        [_cPicker showPicker];
    }
}

UIImage and Memory

+[UIImage imageNamed:]
• Reads the file, uncompresses it, caches result
• Cached copy of data is kept even if the UIImage is deallocated
• Low memory condition causes cache to be purged.
• No direct control over when cache is purged.
• Use for small frequently drawn images.

+[UIImage imageWithContentsOfFile:]
• Just reads enough of file to determine if it can open the file.
• Reads and uncompresses the file each time it draws. Uses uncompressed size worth of memory only temporarily.
• Assigning a UIImage created this way to a UIImageView or as the contents of a CALayer also causes it to read and uncompress the file. The UIImageView or CALayer keep the expanded version.
Continue reading

Simple XML Parser based on NSXMLParser +converter

Simple XML Parser based on NSXMLParser +converter to XML file

How To Setup:
insert next code to file “name of you project”_Prefix.pch

1
2
3
     #import "XMLNode.h"
     #import "XMLParser.h"
     #import "XMLConvert.h"

Create and launching XMLParser.
You will get parsed data ( with XMLNode data type ) in callbackParser: method

1
2
3
4
5
6
7
8
     NSURL *URLToFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
    pathForResource:@"source"
     ofType:@"xml"]];
     
     XMLParser *parser = [[XMLParser alloc] init];
     [parser setDelegate:self withAction:@selector(callbackParser:)];
     [parser parseXMLFile:URLToFile];
     [parser release];

Converting results of parsing to XML file:

1
  NSString *content = [XMLConvert convertXMLNode:root];

And additional define methods for working with XMLNode’s:
XMLaddAttribute(node, object, key), XMLgetAttribute(node, key), XMLsetParent(node, parent), XMLaddChild(parent, child), XMLgetChild(parent, child), XMLremoveChild(parent, child), XMLgetChildWithAttribute(parent, childname, object, key)


Good luck!

UPDATE
More easy convert to XML, but in that solution we use custom nodes

1
2
3
4
NSStirng *error;
NSDate *xmlData = [NSPropertyListSerialization dataFromPropertyList:dictionary
                                                             format:NSPropertyListXMLFormat_v1_0
                                                   errorDescription:&error];

Tutorial: Drag and Drop file on NSImageView

Step by step for starter developers…

1. Create a project in xCode with name “DragAndDrop” or any else…2. Add an element “NSImageView” on main view in the MainMenu.xib

Continue reading

Universal web services suite for iPhone/iPad and Android apps

Hi there! We are a group of iPhone / Android developers who have developed a suite of web services to assist us and other developers in building great apps.

After numerous projects we have become tired of having to set up the server scripts to do all the same things for different clients. Most of the server functionality

is typical: 1) storing location data for Google Maps; 2) storing users’ high scores / ranks; 3) sending Push Notifications; 4) storing files / XML; etc.

We couldn’t use the existent solutions because in some cases they didn’t provide the required functionality and in most cases they require your users to be exposed to some social network of theirs, while our clients just want a simple functionality without users knowing of any services behind that.

So we have launched what we call Mob1serv, a universal server solution for the typical needs of iPhone / Android apps. It consists of modules which deal with most common tasks:

* High Scores – a powerful online high scores table
* PushNote – a module allowing to send immediate or delayed Push Notifications (you can build instant messengers or alarm clocks, anything with this)
* GeoPos – stores locations of Google Map objects, their statuses and ‘last seen online’ time
* OAuth contracter – allows you to implement transparent authentication and integration with Facebook, Twitter, Google etc
* More modules to come!

Continue reading

Use Matrix of rotate +MozOrientation

Previous post is simple example of usage MozOrientation. But now i use Matrix of rotate and i have nice animation.

You can read many information about Matrix of rotate here. These methods are used in game development, make animations and many others.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var context = drawingCanvas.getContext('2d');

var xc = 75;
var yc = 75;
var xi = 0;
var yi = 0;

var myImage = new Image();

var angle = (Math.PI/2)*-o.x;
myImage.onload = function() {
     context.clearRect(0,0,150,150);
     context.save();
     
     xi = xi*Math.cos(angle)-yi*Math.sin(angle)-xc;
     yi = yi*Math.sin(angle)+yi*Math.cos(angle)-yc;
     
     
     context.translate( xc , yc);
     
     context.rotate(angle);
     context.scale(1+o.y,1+o.y);
     context.drawImage(myImage, xi, yi);
     
     context.restore();
}
myImage.src = "feedme.png";

Result:

Your browser doesn’t support canvas.


Continue reading

Resize and Mask an Image

Make image with a mask!


Source:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
- (UIImage*) maskImage:(UIImage *)image  {
     
     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
     
     UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
     CGImageRef maskImageRef = [maskImage CGImage];
     
     // create a bitmap graphics context the size of the image
     CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
     
     
     if (mainViewContentContext==NULL)
          return NULL;
     
     CGFloat ratio = 0;
     
     ratio = maskImage.size.width/ image.size.width;
     
     if(ratio * image.size.height < maskImage.size.height) {
          ratio = maskImage.size.height/ image.size.height;
     }
     
     CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
     CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};
     
     
     CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
     CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
     
     
     // Create CGImageRef of the main view bitmap content, and then
     // release that bitmap context
     CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
     CGContextRelease(mainViewContentContext);
     
     UIImage *theImage = [UIImage imageWithCGImage:newImage];
     
     CGImageRelease(newImage);
     
     // return the image
     return theImage;
}

Download Sources of Project

Continue reading

touchBegan/touchEnd in custom UIWebView

The main disadvantage in the object UIWebView is lack of methods touchBegan and touchEnd. But this question has been settled by some manipulations with privates possibilities:) Thank you Satoshi Nakagawa :)

PSWebView.h – empty

1
2
3
4
5
#import

@interface PSWebView : UIWebView
@end
</uikit>

If you need add method touchBegan then make step by step
1. add after 6 line

1
- (void)webView:(UIWebView*)sender tappedBeganWithTouch:(UITouch*)touch event:(UIEvent*)event;

2. after 11

1
- (void)fireBeganTappedWithTouch:(UITouch*)touch event:(UIEvent*)event;

3. add after 31

1
2
3
4
5
6
7
8
9
10
11
- (void)__touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
     [self __touchesBegan:touches withEvent:event];
     
     id webView = [[self superview] superview];
     if (touches.count == 1) {
          if ([webView respondsToSelector:@selector(fireBeganTappedWithTouch:event:)]) {
               [webView fireBeganTappedWithTouch:[touches anyObject] event:event];
          }
     }
}

4. after 46

1
2
3
     Method targetMethod2 = class_getInstanceMethod(klass, @selector(touchesBegan:withEvent:));
     Method newMethod2 = class_getInstanceMethod(klass, @selector(__touchesBegan:withEvent:));
     method_exchangeImplementations(targetMethod2, newMethod2);

5. and last addition in source before last “@end”

1
2
3
4
5
6
- (void)fireBeganTappedWithTouch:(UITouch*)touch event:(UIEvent*)event
{
     if ([self.delegate respondsToSelector:@selector(webView:tappedBeganWithTouch:event:)]) {
          [(NSObject*)self.delegate webView:self tappedBeganWithTouch:touch event:event];
     }
}

For touchMoves similar steps. It’s easy!

Continue reading

UIScrollView and touchesBegan/touchesEnded

Не работает touchesBegan и touchesEnded в UIScrollView
Что делать?

Много людей пишет об этой проблеме. Для себя я нашел не совсем стандартное решение.

К примеру есть контроллер X в котором наш UIScrollView. в этом же контроллере создадим UIView, но не совсем стандартный, а подготовленный зараннее и передюющий все ивенты  в наш контроллер X и вставим его в UIScrollView.

К примеру такой код должен содержать подготовленный UIView объект:

1
2
3
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     [наш_контроллер_X touchesBegan:touches withEvent:event];
}

Как вы будете добираться до своего контроллера X, это уже ваша смекалка.

Может это и велосипед, но думаю есть и более сложные способы :)

Связываем UITableView и UISearchBar

Опишу как связывал UITableView и UISearchBar. Вот пару примеров:

BNB Skeleton

К примеру у нас есть indexArray (NSArray) c объектами NSString. Нужно засунуть этот массив в табличку и связать с поисковой панелью.
Прежде рекомендую отсортировать весь массив, т.к. он в UITableView будет отсортирован только по заглавным буквам.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 NSInteger alphabeticSort(id string1, id string2, void *reverse)
{
    if ((NSInteger *)reverse == NO) {
         
        return [string2 localizedCaseInsensitiveCompare:string1];
         
    }
    return [string1 localizedCaseInsensitiveCompare:string2];
}

        //Example
        int reverseSort = NO;
     NSArray *temp = [indexArray sortedArrayUsingFunction:alphabeticSort context:&reverseSort];
     
     [indexArray removeAllObjects];
     [indexArray release];
     indexArray = [[NSMutableArray alloc] initWithArray:temp];

Так, массив есть отсортированный.
Далее создаем *UIViewController*. Может спросите почему именно такой контроллер :) Отвечу сразу. Мне проще с ним, в нем нету лишнего, лучше вставить свой код. Если чего-то не хватает, то можно всегда открыть документацию в xcode или залесть в тот же framework и прочесть, что есть в том же UITableViewController’е .

Continue reading

1 2 Next »