您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 為圖片加上文字浮水印:UIImage 類別實作教學

編輯:iOS 開發綜合

在 iOS 上替圖片加上浮水印文字,最乾淨的做法是替 UIImage 擴充一個類別(Category),讓任何一張圖片都能直接呼叫這個方法。下面一步步來。

第一步:建立 UIImage 的類別

檔名命名為 UIImage+watermark。標頭檔內容如下:

#import 

@interface UIImage (watermark)

// 對外暴露的方法
- (UIImage *)watermarkImage:(NSString *)text;

@end

第二步:實作繪製邏輯

實作檔的核心思路是「開啟繪圖上下文 → 畫原圖 → 疊上文字 → 取出結果」:

#import "UIImage+watermark.h"

@implementation UIImage (watermark)

- (UIImage *)watermarkImage:(NSString *)text
{
    // 1. 建立與原圖同尺寸的繪圖上下文
    UIGraphicsBeginImageContext(self.size);

    // 2. 先把原圖畫上去
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];

    // 3. 決定浮水印文字的擺放區域(貼齊底部)
    CGRect rect = CGRectMake(0, self.size.height - 20, self.size.width, 20);

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentCenter;

    // 文字屬性:字級、段落樣式、顏色
    NSDictionary *dic = @{
        NSFontAttributeName : [UIFont systemFontOfSize:13],
        NSParagraphStyleAttributeName : style,
        NSForegroundColorAttributeName : [UIColor whiteColor]
    };

    // 把文字畫上去
    [text drawInRect:rect withAttributes:dic];

    // 4. 從上下文取出成品圖片
    UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();

    // 5. 關閉上下文,避免記憶體洩漏
    UIGraphicsEndImageContext();

    return watermarkImage;
}

@end

幾個實作細節值得留意:文字區域的高度直接寫死為 20,實務上可依字級調整;段落樣式讓文字水平居中;最後務必呼叫 UIGraphicsEndImageContext() 收尾,否則上下文不會被釋放。

第三步:在畫面上使用

在 ViewController 中引入類別標頭,然後像呼叫原生方法一樣使用即可:

#import "ViewController.h"
#import "UIImage+watermark.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *image = [UIImage imageNamed:@"baymax.jpg"];

    // 一行搞定:呼叫類別方法加上浮水印
    UIImage *img = [image watermarkImage:@"@大白"];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imageView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // 釋放可重建的資源
}

@end

這個寫法的好處是複用性高:專案裡任何需要浮水印的地方,只要拿到一張 UIImage,就能直接轉換,不必重複撰寫繪圖程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved