iOS | 圖片打水印

這個(gè)功能前前后后很多細(xì)節(jié),也饒了很多彎路,最后核心功能總結(jié)如下。

一、添加圖片水?。ㄈ缣砑庸緇ogo)

也就是將兩張圖片合成,一張是需要添加的水印,一張是原圖片。
以下是添加水印代碼

image = [self addPrintImg:self.waterImgView.image toOriginImg:image andWithWMType:WMTypeWaterMark];

/**
 *  繪制位圖
 *
 *  @param print    將要添加的圖片
 *  @param Origin   原圖
 *
 *  @return 已打好水印的圖片
 */
- (UIImage *)addPrintImg:(UIImage *)print toOriginImg:(UIImage *)Origin andWithWMType:(WMType)type
{
    //繪制位圖的大小
    UIGraphicsBeginImageContext(Origin.size);
    //Draw Origin
    [Origin drawInRect:CGRectMake(0, 0, Origin.size.width, Origin.size.height)];
    
    //Draw print  將要添加水印的位置x、y和寬高(這里的寬高最好是設(shè)為原圖的寬高比,以便適配各種像素)
    [print drawInRect:CGRectMake(waterImg_x, waterImg_y, printWidth, printHeight)];
        
    //返回的圖形大小
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //end
    UIGraphicsEndImageContext();
    
    return resultImage;
}

二、添加動(dòng)態(tài)數(shù)據(jù)水?。ㄈ缣砑訑?shù)字、文字等)

以下是將動(dòng)態(tài)數(shù)據(jù)添加到圖片代碼

image = [self imageWithStringWaterMark:@"我是文字" atPoint:CGPointMake(x,y) atFont:[UIFont fontWithName:@"Marker Felt" size:20.f] andImg:image];
/**
 *
 *  @param markString   將要添加的文字
 *  @param point    將要添加的文字在圖片上的位置
 *  @param font      文字大小   
 *  @param image  將要添加文字的圖片
 * 
 *  @return 已打好水印的圖片
 */
- (UIImage *)imageWithStringWaterMark:(NSString *)markString atPoint:(CGPoint)point atFont:(UIFont*)font andImg:(UIImage *)image
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
    {
        UIGraphicsBeginImageContextWithOptions([image size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
    }
#else
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0)
    {
        UIGraphicsBeginImageContext([image size]);
    }
#endif
    
    // 繪制文字
    //文字顏色
    UIColor *magentaColor   = [UIColor whiteColor];
    [magentaColor set];
    
    //原圖
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    
    //文字類(lèi)型
    UIFont *helveticaBold = font;
    
    //水印文字
    [markString drawInRect:CGRectMake(point.x, point.y, image.size.width, image.size.height)
           withAttributes:@{NSFontAttributeName: helveticaBold,
                            NSForegroundColorAttributeName: magentaColor
                            }];
    //返回新的圖片
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newPic;
}

效果圖:

背景圖+(水?。┐馗襁\(yùn)動(dòng)logo圖片+(水?。?3.69KM數(shù)字或文字

如有不妥之處望能指正!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容