iOS2012. 9. 13. 11:02

UIImageView를 둥글게 제가 사용한 방법 입니다.
#import <QuartzCore/QuartzCore.h> 이렇게 한 후
imageView.layer.masksToBounds = YES;
imageView.layer.cornerRadius = 5;
이걸 쓰면 둥글게 되더군요.
cornerRadius 의 수치가 둥글게 정도의 수치구요.

Posted by 다오나무
iOS2012. 9. 13. 11:01

그림 1.



Corner에 라운드가 처리된 ImageView가 필요해서, 만들게 되어 이러게 공유 합니다 ^^

구글링 해보면, 이런저런 기법들이 많이 나오는데요, 복잡한 해법들이 많은데,
저는 UIBeizerPath라는 녀석을 이용해서, 간단히 구현 하는 방법을 소개 해볼까 합니다.

아직 UIImageView를 이용하면 가장 좋을것 같은데, 방법을 따로 못찾아서, UIView를 상속 받아서, 구현하였습니다.
혹시 아시는 분 있으면 공유! 부탁드립니다 !

RoundRectedImageView.h

#import <Foundation/Foundation.h>

@interface RoundRectedImageView : UIView {

}

@property (nonatomic,retainUIImage *image;

-(id) initWithImage:(UIImage *) aImage;

@end


RoundRectedImageView.m

#import "RoundRectedImageView.h"


@implementation RoundRectedImageView

@synthesize image = mImage;

-(id) initWithImage:(UIImage *) aImage {

    

    self = [super initWithFrame:CGRectMake(00, aImage.size.width, aImage.size.height)];

    self.image = aImage;

    self.backgroundColor = [UIColor clearColor];

    return self;

}


-(void) drawRect:(CGRect)rect {

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerAllCornerscornerRadii:CGSizeMake(16.016.0f)];

    [path addClip];

    [self.image drawInRect:rect];

}

-(void) dealloc {

    self.image = nil;

    [super dealloc];

@end


코드양이 별로 없어서, 설명도 간략하겠군요 :)
drawRect: Method만 살펴 보시면 됩니다.

1. Round가 있는 사각형 UIBezierPath Object를 만든다.
2. addClip 을 호출하여, 앞으로 그려질때, clipping 되도록한다.
3. UIImage를 그려준다.



이렇게 해주면 그림.1 의 우측 그림과 같이 RoundRect 된 ImageView가 됩니다. ^^

Posted by 다오나무
iOS2012. 9. 10. 21:57

iOS 개발 하다 보니 image를 crop 하거나 resize를 해야 하는 경우가 많더구요.

구글링 해보니 괜찮게 만들어 놓은 소스도 많아서 참고해서 UIImage에 Category로 만들어서 사용하고 있습니다. 


  1. @implementation UIImage ( NBUIImageCrop )
  2. - (UIImage *)crop:(CGRect)rect {
  3.     if (self.scale > 1.0f) {
  4.         rect = CGRectMake(rect.origin.* self.scale,
  5.                           rect.origin.* self.scale,
  6.                           rect.size.width * self.scale,
  7.                           rect.size.height * self.scale);
  8.     }
  9.    
  10.     if ([self imageOrientation] == UIImageOrientationLeft) {
  11.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  12.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  13.         rect.origin = CGPointMake(rect.origin.y, rect.origin.x);
  14.     }
  15.     else if ([self imageOrientation] == UIImageOrientationRight) {
  16.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  17.         rect.origin = CGPointMake(rect.origin.y, rect.origin.x);
  18.     }
  19.  
  20.     CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
  21.     UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
  22.     CGImageRelease(imageRef);
  23.     return result;
  24. }
  25.  
  26. - (UIImage *)resizeToFitWidth:(CGFloat)width
  27. {
  28.     CGSize size = CGSizeMake(width, self.size.height * width/self.size.width);
  29.     UIGraphicsBeginImageContext(size);
  30.     [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  31.     UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  32.     UIGraphicsEndImageContext();
  33.     return newImage;
  34. }

Posted by 다오나무
iOS2012. 9. 9. 19:24

- (NSString *)getFileName {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyyMMdd_hhmmss_"];

NSDate *date = [[NSDate alloc] init];

NSString *fileName = [NSString stringWithFormat:@"%@%@",

  [dateFormatter stringFromDate:date],

  [[[NSString stringWithFormat:@"%f", [[NSDate date]timeIntervalSince1970]] componentsSeparatedByString:@"."] objectAtIndex:1]];

[date release];

[dateFormatter release];

return fileName;

}

Posted by 다오나무
iOS2012. 9. 4. 22:27


UITextView: move view when keyboard appears
                                                                           For showing the textview fields without being hidden by the keyboard, the standard way is to move up/down the view having text fields whenever the keyboard is shown.

                
        
The following simple steps is used to move up/down the UITextField in your iPhone.

Step 1: Set the UITextViewDelegate, and tag the textViewFields (in your .hfile)

Step 2: Place "CGFloat animatedDistance;" in to inside the interface (in your .h file)

Step 3:  Define the following values in top of your .m file (after @implimentation)     

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

Step 4: And finally add the following code into your .m file          
 
-(void) textViewDidBeginEditing:(UITextView *)textView {
    
    CGRect textFieldRect = [self.view.window convertRect:textView.bounds fromView:textView];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    
    if(heightFraction < 0.0){
        
        heightFraction = 0.0;
        
    }else if(heightFraction > 1.0){
        
        heightFraction = 1.0;
    }
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if(orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown){
        
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
        
    }else{
        
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
 if([text isEqualToString:@"\n"])
 {
  [textView resignFirstResponder];
  return NO;
 }
 return YES;
}

iphone - How to dismiss keyboard for UITextView with return key:
               Did you saw the last para of the above code snippets?, that is used to hide the iphone keypad when clicking return key.

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
 if([text isEqualToString:@"\n"])
 {
  [textView resignFirstResponder];
  return NO;
 }
 return YES;
}
Please share this post. If it's useful to you.

Posted by 다오나무
iOS2012. 9. 4. 16:25

iOS에서 네비게이션바에 이미지를 설정하는 함수가 생겼다.


setBackgroundImage:forBarMetrics:


이 함수로 이미지만 설정하면 간단하나, 문제는 iOS4이하에서의 설정방법


따라서 아래와 같이 설정하면 iOS 버전과 관련 없이 모두 적용할 수 있다.


viewDidLoad 같은 곳에서 설정하면 됨


 UIColor *color = [UIColor colorWithRed:0.94 green:0 blue:0.44 alpha:1.0];

    self.navigationController.navigationBar.tintColor = color;

UIImage *imageNavCon = [UIImage imageNamed:@"background.png"];

if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])

    {

        [self.navigationController.navigationBar setBackgroundImage:imageNavConforBarMetrics:UIBarMetricsDefault];

    }

else {

[self.navigationController.navigationBar insertSubview:[[[UIImageView allocinitWithImage:imageNavCon]autoreleaseatIndex:0]; 

}

Posted by 다오나무
iOS2012. 9. 4. 15:45

*1번째 간단한 방법(Action 버튼 생성)*
장점 : 상당히 쉽게 만들수 있음.
단점 : 버튼이 터치되는 영역이 실제 버튼보다 훨 씬 넓음.

UIBarButtonItem *composerBtn =[[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemAction target:selfaction:@selector(composerMethode)];


*2번째 방법 : 시스템아이템 버튼이 아닌 임의의 이미지를 이용하여 버튼 구성 방법*

장점 : 버튼의 외각 이미지 + 내부 추가한 이미지(i.png)표현 가능.
단점 : 버튼이 터치되는 영역이 실제 버튼보다 훨 씬 넓음.


UIImage *image = [UIImage imageNamed:@"i.png"];

image = [UIImage imageWithCGImage:[image CGImagescale:2.0 orientation:UIImageOrientationUp];

UIBarButtonItem *editButton = [[UIBarButtonItem alloc

                                       initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(editDB)];

        

self.navigationItem.leftBarButtonItem = editButton;


*3.번째 방법 : 임의의 뷰에 UIButton을 추가하여 구성하는 방법*
목적 : 1번째,2번째 방법의 단점을 해결하고자 함.
장점 : 정확히 버튼의 크기만큼만 터치가 됨.
단점 : 시스템에 있는 버튼아이템이미지 사용 불가. , 버튼의 외각 이미지 표현 불가.

            UIView *rightview = [[UIView allocinitWithFrame:CGRectMake(0,0,25,20)];

            

            UIButton *searchbutton = [[UIButton allocinitWithFrame:CGRectMake(0,0,2520)];


            UIImage *image = [UIImage imageNamed:@"action.png"];

            image = [UIImage imageWithCGImage:[image CGImagescale:1.0 orientation:UIImageOrientationUp];

            

            [searchbutton setImage:image forStateUIControlStateNormal];


            [searchbutton addTarget:self action:@selector(composerMethode) forControlEvents:UIControlEventTouchUpInside];

            [rightview addSubview:searchbutton];

            [searchbutton release];

            

            UIBarButtonItem *composerBtn = [[UIBarButtonItem allocinitWithCustomView:rightview];

            [rightview release];

Posted by 다오나무
iOS2012. 9. 4. 11:31

UIColor에 카테고리로 추가해서 사용합니다.


- 파일명 : UIColor+FWExtension.h

@interface UIColor (FWExtension)

+(UIColor *)colorWithRGB:(NSInteger)rgbValue;

@end


- 파일명 : UIColor+FWExtension.m

@implementation UIColor (FWExtension)

+(UIColor *)colorWithRGB:(NSInteger)rgbValue {

float redValue   = ((float)((rgbValue & 0xFF0000) >> 16)) / 255.0;

float greenValue = ((float)((rgbValue &   0xFF00) >>  8)) / 255.0;

float blueValue  = ((float)((rgbValue &     0xFF) >>  0)) / 255.0;

return [UIColor colorWithRed:redValue green:greenValue blue:blueValue alpha:1.0];

}

@end

Posted by 다오나무
iOS2012. 9. 4. 11:30

iPhone 앱에서 RGB 값 사용하기

애플에서 일반적으로 자주쓰는 Hex RGB 가 아니라, 각 RGB,A값을 0 에서 1.0 으로 설정하는 RGB 설정 메서드를 제공하므로 hex RGB 는 직접 관련 메서드를 만들어 사용해야 한다.

필요하시면 아래의 메서드를 사용하세요 ^^
 


- (UIColor *) myRGBfromHex: (NSString *) code {

    NSString *str = [[code stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]] uppercaseString];

    

    if ([str length] < 6)  // 일단 6 이하면 말이 안되니까 검은색을 리턴해주자.

        return [UIColor blackColor];

    // 0x 시작하면 0x 지워준다.

    if ([str hasPrefix:@"0X"])

        str = [str substringFromIndex:2];

    // #으로 시작해도 # 지워준다.

    if ([str hasPrefix:@"#"])

        str = [str substringFromIndex:1];

    if ([str length] != 6//그랫는데도 6자 이하면 이것도 이상하니 그냥 검은색을 리턴해주자.

        return [UIColor blackColor];

   

    NSRange range;

    range.location = 0;

    range.length = 2;

    NSString *rcolorString = [str substringWithRange:range];

    range.location = 2;

    NSString *gcolorString = [str substringWithRange:range];

    range.location = 4;

    NSString *bcolorString = [str substringWithRange:range];

    unsigned int red, green, blue;

    [[NSScanner scannerWithString: rcolorString] scanHexInt:&red];

    [[NSScanner scannerWithString: gcolorString] scanHexInt:&green];

    [[NSScanner scannerWithString: bcolorString] scanHexInt:&blue];

    

    return [UIColor colorWithRed:((float) red / 255.0f)

                           green:((float) green / 255.0f)

                            blue:((float) blue / 255.0f)

                           alpha:1.0f];

}

Posted by 다오나무
iOS2012. 9. 4. 11:02

How to Customize UITabBar on iOS 5

Building the new version of the app Blocos de Rua I was challenged to customize the UITabBar so it meets what the designer wants. In iOS 5 this is pretty easy to do but I haven’t figured out the proper way to do it from the beginning, this post is my findings on how to do it properly by correctly using the new iOS 5 APIs to customize appearance.

The final look:

Keep reading to see the code.

The appearance APIs in iOS 5 are great. They reduce lots of custom drawRect: that used to be necessary to customize the default UIKit components. The first time I tried to customized the tab bar I had some problems with images been offset upwards because I was using the wrong methods.First thing I learned, the setFinishedSelectedImage:finishedUnselectedImage: from UITabBarItem is the tab’s icon not a image for the whole tab with background, icon and label.

Customize the UITabBar is a peace of cake when you understand how the APIs should be used, take a look:

From inside out, the UITabBar

First - usually in your app delegate - set the image for the entire tab bar’s background, which represents the “normal” state of all tabs. The dimension is 320 x 49 points.

1
[[[self tabBarController] tabBar] setBackgroundImage:[UIImage imageNamed:@"background"]];

Then configure the selected state of a tab. This is necessary because in this app I don’t want the default white highlight that represents the selected tab. Pay attention to the image’s width, it must be the same of a single tab. In my case 320/4, 80 points wide.

1
[[[self tabBarController] tabBar] setSelectionIndicatorImage:[UIImage imageNamed:@"selected"]];

Last but not least, the UITabBarItem

Unlike the default behavior the image shouldn’t change when the tab is selected, this is why I set the same image in both states. For each UIViewController that will be part of the tab bar you need to configure the tab image like this:

1
2
3
4
5
6
7
- (id)init {
    self = [super initWithNibName:@"MyNibName" bundle:nil];
    if (self) {
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"The Title" image:nil tag:0];
        [[self tabBarItem] setFinishedSelectedImage:[UIImage imageNamed:@"tab_icon"] withFinishedUnselectedImage:[UIImage imageNamed:@"tab_icon"]];
    }
}

The last detail is the title’s color on the unselected tab, they can’t be the default gray color. To change the color we need a dictionary of attributes whit the UITextAttributeTextColor key:

1
2
3
4
// below the setFinishedSelectedImage:withFinishedUnselectedImage:
[[self tabBarItem] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
        [UIColor whiteColor], UITextAttributeTextColor,
        nil] forState:UIControlStateNormal];

That’s all folks.

Posted by 다오나무