What are the correct dimensions for a custom tab bar item background image?

后端 未结 6 733
北海茫月
北海茫月 2021-01-13 15:11

So I have a .png that\'s 428x176 px:

I want to use it as a tab bar background image for when an item is in the selected state. The problem is t

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 15:26

    Making my answer for this question how to make UITabBar selection indicator image fill the whole space? as reference:

    Subclass the UITabBarController

    It works for multiple devices even with rotation.

    Notes:

    1. Make your images' rendering mode as Original.
    2. Assign this class below to your UITabBarController in your Storyboard or as your base class if you're doing your screen programmatically.

      //
      //  BaseTabBarController.swift
      //  MyApp
      //
      //  Created by DRC on 1/27/17.
      //  Copyright © 2017 PrettyITGirl. All rights reserved.
      //
      
      import UIKit
      
      class BaseTabBarController: UITabBarController {
      
          let numberOfTabs: CGFloat = 4
          let tabBarHeight: CGFloat = 60
      
          override func viewWillAppear(_ animated: Bool) {
              super.viewWillAppear(animated)
      
              updateSelectionIndicatorImage()
          }
      
          override func viewWillLayoutSubviews() {
              super.viewWillLayoutSubviews()
      
              updateSelectionIndicatorImage()
          }
      
          func updateSelectionIndicatorImage() {
              let width = tabBar.bounds.width
              var selectionImage = UIImage(named:"myimage.png")
              let tabSize = CGSize(width: width/numberOfTabs, height: tabBarHeight)
      
              UIGraphicsBeginImageContext(tabSize)
              selectionImage?.draw(in: CGRect(x: 0, y: 0, width: tabSize.width, height: tabSize.height))
              selectionImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()
      
              tabBar.selectionIndicatorImage = selectionImage
          }
      
      }
      

提交回复
热议问题