首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 開發:從 32 位整數 (ARGB) 解析顏色生成 UIColor

     編輯:程式設計綜合問答

問題描述

擁有一個 32 位整數 intARGB = 4294967295(即 0xFFFFFFFF),對應 C++ 中的 setRGB() 參數。需在 iOS 中解析出 Alpha、Red、Green、Blue 四個分量並生成 UIColor。

解析邏輯

32 位 ARGB 佈局:AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB(高位到低位)。提取方法:

  • Alpha = (intARGB >> 24) & 0xFF
  • Red = (intARGB >> 16) & 0xFF
  • Green = (intARGB >> 8) & 0xFF
  • Blue = intARGB & 0xFF

代碼實現

uint32_t intARGB = 4294967295; // 0xFFFFFFFF
CGFloat alpha = ((intARGB >> 24) & 0xFF) / 255.0f;
CGFloat red   = ((intARGB >> 16) & 0xFF) / 255.0f;
CGFloat green = ((intARGB >> 8) & 0xFF) / 255.0f;
CGFloat blue  = (intARGB & 0xFF) / 255.0f;

UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
// 結果:白色不透明 colorWithRed:1 green:1 blue:1 alpha:1

封裝為分類方法(推薦)

為 UIColor 添加便利構造器:

// UIColor+Hex.h
@interface UIColor (Hex)
+ (UIColor *)colorWithARGB:(uint32_t)argb;
@end

// UIColor+Hex.m
@implementation UIColor (Hex)
+ (UIColor *)colorWithARGB:(uint32_t)argb {
    return [UIColor colorWithRed:((argb >> 16) & 0xFF)/255.0f
                           green:((argb >> 8) & 0xFF)/255.0f
                            blue:(argb & 0xFF)/255.0f
                           alpha:((argb >> 24) & 0xFF)/255.0f];
}
@end

// 使用
UIColor *c = [UIColor colorWithARGB:0xFFFF0000]; // 紅色不透明

注意事項

  • 確保整數為無符號 32 位(uint32_t),避免符號位擴展導致負數錯誤。
  • 若輸入為 0xRRGGBB(無 Alpha),默認 Alpha=255:colorWithRGB:0xFF0000。
  • UIColor 分量範圍 0.0~1.0,除以 255.0 轉換。

位運算提取顏色分量是跨平台通用技巧,iOS 中配合 UIColor 構造器即可無縫對接 C++ 數據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved