溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

iOS UIImage/UIImageView處理

發(fā)布時間:2020-07-07 14:37:15 來源:網(wǎng)絡 閱讀:3138 作者:zmhot88 欄目:移動開發(fā)

      今天處理了把iOS6版本改為iOS7的過程了,遇到了一些問題,查了一些資料,紀錄一下:

      1,iPad1上,更新圖標以后最后先把原有程序卸載了,要不然圖片殘留很嚴重,還遇到一個問題說是調(diào)試過程中有其他進程在調(diào)試,重啟iPad1就好了。就因為圖片殘留的問題,至少耽擱我1-2小時。

      2,UINavigationBar自定義:看看支持到4.3的解法:

#pragma mark -
#pragma mark 自定義導航欄背景
@implementation UINavigationBar (CustomImage)
- (UIImage *)barBackground
{
    UIImage *bg = [UIImage p_w_picpathNamed:@"bg_navbar_ios7.png"];
    if ([FMUSystem getOSVersion] < 7.0) {
        bg = [FMUImage p_w_picpathByScalingAndCroppingForSize:CGSizeMake(320, 44) SourceImage:bg CropType:FMUIMAGE_SCALE_TYPE_FITMIN];
//        UIGraphicsBeginImageContext(CGSizeMake(320,44));
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        [bg drawInRect: CGRectMake(0, 0, 320,44)];
//        bg = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
    }
                                                                                                                                                                                                         
    return bg;
}
- (void)didMoveToSuperview
{
    //iOS5 only
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];
    }
}
//this doesn't work on iOS5 but is needed for iOS4 and earlier
- (void)drawRect:(CGRect)rect
{
    //draw p_w_picpath
    [[self barBackground] drawInRect:rect];
}
@end


       為了支持iOS7,使用320*64的圖片,還得我自己來裁一下。我個人比較喜歡注釋掉的方法。上面的函數(shù)是其他同事實現(xiàn)的公有方法。

       3,生成圓形圖

       3.1 layer層畫圓角

UIImageView * p_w_picpathView = [[UIImageView alloc] initWithImage:[UIImage p_w_picpathNamed:@"oiuyfdsa.png"]];
p_w_picpathView.frame = CGRectMake(20.f, 20.f, 100.f, 100.f);
p_w_picpathView.layer.masksToBounds = YES;
p_w_picpathView.layer.cornerRadius = 50;

       3.2 畫布畫

-(UIImage*) circleImage:(UIImage*) p_w_picpath withParam:(CGFloat) inset {
    UIGraphicsBeginImageContext(p_w_picpath.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGRect rect = CGRectMake(inset, inset, p_w_picpath.size.width - inset * 2.0f, p_w_picpath.size.height - inset * 2.0f);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
                                                                                                                                                    
    [p_w_picpath drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
    CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}


       4,圖片平鋪的方式

       4.1 圖片轉(zhuǎn)換為uicolor,設為背景,有點像OpenGL中紋理設置。

UIColor *circleColorPattern = [UIColor colorWithPatternImage:
[UIImage p_w_picpathNamed:@"circle_pattern.png"]];

       4.2 圖片轉(zhuǎn)換為類似android中9.png的方式

        iOS5之后:

UIImage *buttonBackgroundImage = [[UIImage p_w_picpathNamed:@"button_bkg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0,13,0,13)];
[button setBackgroundImage:buttonBackgroundImage forState:UIControlStateNormal];

        這是取27個像素,中間那個像素拉伸活者壓縮。

       iOS5之前的方法:

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth
topCapHeight:(NSInteger)topCapHeight;

    這個方法有局限性,它只能指定leftCapWidth和topCapHeight,然后只有一個像素能夠重復,也就是rightCapWidth為 p_w_picpathWidth-leftCapWidth-1,而bottomCapHeight為 p_w_picpathHeight - topCapHeight -1,所以重復的始終是中間的那一個像素.


    最后摘錄一份iOS6,7的適配文章,這文章已經(jīng)看過2遍以上,可是需要的時候還要查,所以放在這里。

Like many of you, I have been very busy upgrading my apps to make them fit for iOS 7. The latest version of iOS introduces lots of visual changes. From a developer’s perspective, the navigation bar and status bar are two noticeable changes that need to cater. The status bar is now transparent, that means the navigation bar behind it shows through. In some cases, the background p_w_picpath for a navigation bar can extend up behind the status bar.

Some time ago, I’ve written a tutorial about how to customize a navigation bar. I think it’s time to revisit the customization and see how it is done in iOS 7. Here are some of the tips and tricks that you’ll find in this article:

  • Setting the background color of navigation bar

  • Using background p_w_picpath in navigation bar

  • Customizing the color of back button

  • Changing the font of navigation bar title

  • Adding multiple bar button items

  • Changing the style of status bar

  • Hiding the status bar

iOS UIImage/UIImageView處理

You’ll need Xcode 5 to properly execute the code as presented in this tutorial. So if you’re still using older versions of Xcode, make sure you upgrade to Xcode 5 before running the sample Xcode project.

Default Navigation Bar in iOS 7

Before we go in to the customization, let’s first take a look at the default navigation bar generated by Xcode 5 and iOS 7. Simply create a Xcode project using Single View Controller template. Embed the view controller in a navigation controller. If you don’t want to start from scratch, you can justdownload this sample Xcode project.

Xcode 5 bundles both iOS 6 and iOS 7 Simulators. Try to run the sample project using both versions of Simulators.

iOS UIImage/UIImageView處理

As you can see, the navigation bar in iOS 7 is by default intertwined with the status bar. The default color is also changed to light gray, as well.

Changing the Background Color of Navigation Bar

In iOS 7, the tintColor property is no longer used for setting the color of the bar. Instead, use the barTintColor property to change the background color. You can insert the below code in the didFinishLaunchingWithOptions: of AppDelegate.m.

1
[[UINavigationBar appearance] setBarTintColor:[UIColor yellowColor]];

Here is the result:

iOS UIImage/UIImageView處理

Normally you want to use your own color as the system color doesn’t look nice. Here is a very useful macro for setting RGB color:

1
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Simply put it somewhere at the beginning of AppDelegate.m and use it to create any UIColor object with whatever RGB color you want. Below is an example:

1
[[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0x067AB5)];

By default, the translucent property of navigation bar is set to YES. Additionally, there is a system blur applied to all navigation bars. Under this setting, iOS 7 tends to desaturate the color of the bar. Here are the sample navigation bars with different translucent setting.

iOS UIImage/UIImageView處理

To disable the translucent property, you can simply select the navigation bar in Storyboard. Under Attribute Inspectors, uncheck the translucent checkbox.

iOS UIImage/UIImageView處理

Using Background Image in Navigation Bar

If your app uses a custom p_w_picpath as the background of the bar, you’ll need to provide a “taller” p_w_picpath so that it extends up behind the status bar. The height of navigation bar is changed from 44 points (88 pixels) to 64 points (128 pixels).

You can still use the setBackgroundImage: method to assign a custom p_w_picpath for the navigation bar. Here is the line of code for setting the background p_w_picpath:

1
[[UINavigationBar appearance] setBackgroundImage:[UIImage p_w_picpathNamed:@"nav_bg.png"] forBarMetrics:UIBarMetricsDefault];

The sample Xcode project bundles two different background p_w_picpaths: nav_bg.png and nav_bg_ios7.png. Try to test them out.

iOS UIImage/UIImageView處理

Changing the Font of Navigation Bar Title

Just like iOS 6, you can customize the text style by using the “titleTextAttributes” properties of the navigation bar. You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the following text attribute keys:

  • UITextAttributeFont – Key to the font

  • UITextAttributeTextColor – Key to the text color

  • UITextAttributeTextShadowColor – Key to the text shadow color

  • UITextAttributeTextShadowOffset – Key to the offset used for the text shadow

Here is the sample code snippets for altering the font style of the navigation bar title:

1
2
3
4
5
6
7
NSShadow*shadow =[[NSShadow alloc] init];
   shadow.shadowColor =[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
   shadow.shadowOffset = CGSizeMake(0, 1);
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
                                                          shadow, NSShadowAttributeName,
[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];

If you apply the change to the sample app, the title of navigation bar should look like this:

iOS UIImage/UIImageView處理

Customizing the Color of Back button

In iOS 7, all bar buttons are borderless. The back button is now a chevron plus the title of the previous screen (or just displays ‘Back’ as the button title if the title of the previous screen is nil). To tint the back button, you can alter the tintColor property, which provides a quick and simple way to skin your app with a custom color. Below is a sample code snippet:

1
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

In addition to the back button, please note that the tintColor property affects all button titles, and button p_w_picpaths.

iOS UIImage/UIImageView處理

If you want to use a custom p_w_picpath to replace the default chevron, you can set the backIndicatorImage and backIndicatorTransitionMaskImage to your p_w_picpath.

1
2
[[UINavigationBar appearance] setBackIndicatorImage:[UIImage p_w_picpathNamed:@"back_btn.png"]];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage p_w_picpathNamed:@"back_btn.png"]];

The color of the p_w_picpath is controlled by the tintColor property.

iOS UIImage/UIImageView處理

Use Image as Navigation Bar Title

Don’t want to display the title of navigation bar as plain text? You can replace it with an p_w_picpath or a logo by using a line of code:

1
self.navigationItem.titleView =[[UIImageView alloc] initWithImage:[UIImage p_w_picpathNamed:@"appcoda-logo.png"]];

We simply change the titleView property and assign it with a custom p_w_picpath. This is not a new feature in iOS 7. The code also applies to lower versions of iOS.

iOS UIImage/UIImageView處理

Adding Multiple Bar Button Items

Again, this tip is not specifically for iOS 7. But as some of you have raised such question before, I decide to put the tip in this tutorial. From time to time, you want to add more than one bar button item on one side of the navigation bar. Both the leftBarButtonItems and rightBarButtonItems properties lets you assign custom bar button items on the left/right side of the navigation bar. Say, you want to add a camera and a share button on the right side of the bar. You can use the following code:

1
2
3
4
5
   UIBarButtonItem *shareItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];
   UIBarButtonItem *cameraItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];

NSArray*actionButtonItems = @[shareItem, cameraItem];
   self.navigationItem.rightBarButtonItems = actionButtonItems;

Here is the sample result:

iOS UIImage/UIImageView處理

Changing the Style of Status Bar

In older versions of iOS, the status bar was always in black style and there is not much you can change. With the release of iOS 7, you’re allowed to change the appearance of the status bar per view controller. You can use a UIStatusBarStyle constant to specify whether the status bar content should be dark or light content. By default, the status bar displays dark content. In other words, items such as time, battery indicator and Wi-Fi signal are displayed in dark color. If you’re using a dark background in navigation bar, you’ll end up with something like this:

iOS UIImage/UIImageView處理

In this case, you probably need to change the style of status bar from dark to light. There are two ways to do this. In iOS 7, you can control the style of the status bar from an individual view controller by overriding the preferredStatusBarStyle:

1
2
3
4
-(UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}

For the sample app, simply put the above code in the RecipeNavigationController.m and the status bar will display light content.

iOS UIImage/UIImageView處理

The method introduced above is the preferred way to change the status bar style in iOS 7. Alternatively, you can set the status bar style by using the UIApplication statusBarStyle method. But first you’ll need to opt out the “View controller-based status bar appearance”. Under the Info tab of the project target, insert a new key named “View controller-based status bar appearance” and set the value to NO.

iOS UIImage/UIImageView處理

By disabling the “View controller-based status bar appearance”, you can set the status bar style by using the following code:

1
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

Hiding the Status Bar

In any case you want to hide the status bar, you can override the prefersStatusBarHidden: in your controller:

1
2
3
4
-(BOOL)prefersStatusBarHidden
{
returnYES;
}

Summary

iOS 7 presents developers with new freedom to customize the appearance of navigation bar and status bar. If you’re porting the app from iOS 6 to iOS 7 or creating a brand-new app for iOS 7, I hope you’ll find these tips useful.

For your complete reference, you can download the source code of the demo project from here. Just uncomment any code snippets in the sample project to test out the change.

Like many of you, I’m still exploring all the new changes of iOS 7 SDK. I am by no means an expert on iOS 7. If you find any errors in the article, please do let me know. If you find any tips and tricks related to navigation bar and status bar, please also share with us by leaving comment below。

還有一篇自定義iOS的NavigationBar, 索性放在一起吧。

Previously, in our iOS Programming 101 series, we showed you how to customize the appearance of the Tab Bar. In this tutorial, we’ll continue to talk about UI customization and cover how to use Appearance API to make the Navigation Bar more beautiful.

Here are what you’ll learn in this tutorial:

  1. Customizing the View with background p_w_picpath

  2. Customizing UINavigationBar including background p_w_picpath and text style of title

  3. Customizing the appearance of UIBarButtonItem

As usual, we’re going to illustrate the concept by converting a plain navigation bar to one with customized graphics. However, to help you focus on learning the customization, we’ve prepared the Xcode project for you to start with. Before proceeding, first download the Xcode project here (note: the project is created using Xcode 4.5).

If you build and run the project, you’ll get an app with simple navigation UI. Now we’ll work together to style the navigation bar, customize the bar buttons and assign our own background p_w_picpath for the view.

iOS UIImage/UIImageView處理

Demo App – Custom Navigation Bar


Customizing the View Background

First, we would like to change the background of view controller with our own p_w_picpath. If you open the Xcode project, you’ll see a set of p_w_picpaths that we’ve added for you. To set the background p_w_picpath, open the “RecipeViewController.m” and add the following line of code to the end of “viewDidLoad” method:

1
self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage p_w_picpathNamed:@"common_bg"]];

Apparently, you can use the “backgroundColor” property of the view to change the background color. What you may not know is that you can also use the same property to set the background p_w_picpath. The trick is to create a UIColor object using the “colorWithPatternImage”. During drawing, the p_w_picpath in the pattern color is tiled as necessary to cover the view area.

After the change, compile and run the app. It should like this:

iOS UIImage/UIImageView處理

Customizing the Background of View Area

Styling the UINavigationBar

Prior to iOS 5, developers can only change the style of navigation bar through a handful of properties. But the problem is the change only applies to the navigation bar of a specific view. From iOS 5 and onwards, the SDK allows developers to style the navigation bar by using Appearance API. You can easily customize the appearance of navigation bars throughout the app using the appearance proxy ([UINavigationBar appearance]).

Changing Navigation Bar Background

Open “AppDelegate.m” and add the following in the “application:didFinishLaunchingWithOptions” method:

1
2
3
4
5
6
7
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
   UIImage *navBackgroundImage =[UIImage p_w_picpathNamed:@"navbar_bg"];
[[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];

returnYES;
}

The first line of code creates the UIImage object with our own background p_w_picpath of navigation bar. Then we use the appearance proxy to assign the p_w_picpath.

Customizing the Title Text of Navigation Bar

Next, we’ll change the font style of the title text. You can customize the text style by using the “titleTextAttributes” properties of the navigation bar. You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the following text attribute keys:

  • UITextAttributeFont – Key to the font

  • UITextAttributeTextColor – Key to the text color

  • UITextAttributeTextShadowColor – Key to the text shadow color

  • UITextAttributeTextShadowOffset – Key to the offset used for the text shadow

In the “application:didFinishLaunchingWithOptions” method of AppDelegate.m, add the following code:

1
2
3
4
5
6
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],
                                                          UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], UITextAttributeFont, nil]];

The above code alters the text style of navigation bar title. We use the HelveticaNeue-CondensedBlack as the font type, set the color to white and add a shadow to the text.

Now compile and run the app again. This is what the customized navigation bar looks like:

iOS UIImage/UIImageView處理

Navigation Bar with customized background and text style

Customizing the Appearance of UIBarButtonItem

Lastly, we’re going to change the appearance of back button, as well as, other navigation bar buttons (i.e. UIBarButtonItem). Again, open “AppDelegate.m” and add the following code in the “application:didFinishLaunchingWithOptions” method:

1
2
3
4
5
6
7
// Change the appearance of back button
   UIImage *backButtonImage =[[UIImage p_w_picpathNamed:@"button_back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

// Change the appearance of other navigation button
   UIImage *barButtonImage =[[UIImage p_w_picpathNamed:@"button_normal"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)];
[[UIBarButtonItem appearance] setBackgroundImage:barButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

We first create the UIImage objects using our own p_w_picpaths (i.e. button_back.png and button_normal.png) and then set the p_w_picpath object as the background p_w_picpath of the UIBarButtonItem. But what’s the resizableImageWithCapInsets: method for? The buttons in navigation bar are not in fixed size. It’ll be automatically resized depending on the text length of the button. For round rectangular button, you probably don’t want to stretch the button in all directions. So we use the resizableImageWithCapInsets: method to add cap insets to the p_w_picpath. During resizing of the p_w_picpath, areas covered by a cap are not resized. The below illustration will give you a better idea about the cap inset:

iOS UIImage/UIImageView處理

resizableImageWithCapInsets illustrated

We define the cap inset using the UIEdgeInset structure. The UIEdgeInsets is structure that specifies float values for each cap inset: top, left, bottom and right areas of an p_w_picpath. For instance, line 1 of the above code instructs iOS that the left 13 pixels and the right 6 pixels of the back button p_w_picpath are not scaled or resized.

After making the code change, compile and run the app again. You should now have the custom back and edit buttons.

iOS UIImage/UIImageView處理

Navigation Bar with customized UIBarButtonItems




向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI