Just My Life & My Work

有時候一張影像,我們想要複製來使用,那麼可以如何做?

[iOS] 拷貝影像 (Copy Image)3

我想拷貝上圖下方的黑色漸層影像

有人如我直覺使用Copy功能,可是會crash,因為:

UIImageView doesn’t conform to NSCopying, but it does conform to NSCoding. Archive your view, and then de-archive it to get a brand new copy.

/**
 Theme: Copy ImageView
 IDE: Xcode 9
 Language: Objective C
 Date: 107/07/12
 Author: HappyMan
 Blog: https://cg2010studio.com/
 */

    UIImageView *imageView = [[UIImageView alloc] initWithImage:darkImage];
    imageView.frame = CGRectMake(0, 0, sleepStateInfoView.frame.size.width, sleepStateInfoView.frame.size.height);
    [sleepStateInfoView addSubview:imageView];
    [sleepStateInfoView sendSubviewToBack:imageView];

    NSData *imageViewData = [NSKeyedArchiver archivedDataWithRootObject:imageView];
    UIImageView *copyImageView = [NSKeyedUnarchiver unarchiveObjectWithData:imageViewData];
    [lifeStyleInfoView addSubview:copyImageView];
    [lifeStyleInfoView sendSubviewToBack:copyImageView];

    imageViewData = [NSKeyedArchiver archivedDataWithRootObject:imageView];
    copyImageView = [NSKeyedUnarchiver unarchiveObjectWithData:imageViewData];
    [respirationRateInfoView addSubview:copyImageView];
    [respirationRateInfoView sendSubviewToBack:copyImageView];

    imageViewData = [NSKeyedArchiver archivedDataWithRootObject:imageView];
    copyImageView = [NSKeyedUnarchiver unarchiveObjectWithData:imageViewData];
    [sdnnInfoView addSubview:copyImageView];
    [sdnnInfoView sendSubviewToBack:copyImageView];

於是乎,我們輕鬆愉快複製和貼上:)

參考:How do you create a copy of an UIImageView instance?

廣告

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: