草庐IT

objective-c - 用它的所有 subview 给 UIView 着色

coder 2023-09-21 原文

有什么方法可以为 UIView 着色?不是背景颜色,而是整个 UIView 及其所有 subview 。

例如 - 带有星星旋转动画的 UIView,即 UIView 形状不断变化。

最佳答案

最后我创建了一个 UIView 类别,它可以对 UIView 进行着色, 不填充 UIView 矩形,这里是:

Takes an image representation of the UIView, then colors it in the given UIColor, this category was created to replicate a UIButton default highlight behavior, so it also comes with a method that can activate that behavior and let the category handle all touch methods.

//------------------ .h Interface file ------- //

//
//  UIView UIView_Tint.h
//  BabyQA
//
//  Created by yogev shelly on 8/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

#define tintColorClassicUIButton [UIColor colorWithWhite:0.0 alpha:0.5]

@interface UIView(Tint)

//proprties should not be used, use the methods decalred bellow
@property (nonatomic,retain) UIColor* tintColor;
@property(nonatomic,retain) UIImageView* tintImageView;
@property(nonatomic,assign) BOOL tintOnTouchActive;

-(void)tintToColor:(UIColor*)color;
-(void)clearTint;
-(void)enableTintOnTouchWithColor:(UIColor*)color;
-(void)disableTintOnTouch;

-(UIImage *)imageRepresentation;
-(UIImage*)imageRepresentationWithTintColor:(UIColor*)color;

@end



//------------------ .m Implementation file ------- //


//  UIView UIView_Tint.m
//  BabyQA
//
//  Created by yogev shelly on 8/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights not reserved - go wild!
//

#import "UIView Tint.h"
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>

static char const * const tintImageViewKey = "tintImageView";
static char const * const tintColorKey = "tintColorKey";
static char const * const tintOnTouchActiveKey = "tintOnTouchActive";



@implementation UIView (Tint)
@dynamic tintImageView;
@dynamic tintColor;
@dynamic tintOnTouchActive;

-(void)enableTintOnTouchWithColor:(UIColor*)color
{
    self.tintColor = color; 
    self.tintOnTouchActive = TRUE;
}

-(void)disableTintOnTouch
{
    self.tintOnTouchActive = FALSE;

}


-(void)tintToColor:(UIColor*)color
{

    if(![self.tintColor isEqual:color] || !self.tintImageView)
    {
        self.tintColor = color;
        UIImage* tintImage = [self imageRepresentationWithTintColor:self.tintColor];
        self.tintImageView =  [[[UIImageView alloc] initWithImage:tintImage] autorelease];
    }

    [self addSubview:self.tintImageView];
}

-(void)clearTint
{
    [self.tintImageView removeFromSuperview];
}

-(void)clearTintWithSecondsDelay:(float)delay
{
    [self performSelector:@selector(clearTint) withObject:self afterDelay:delay];
}


#pragma mark - TouchToggling

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    if(self.tintOnTouchActive)
        [self tintToColor:self.tintColor];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    if(self.tintOnTouchActive)
        [self clearTintWithSecondsDelay:0.05];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    if(self.tintOnTouchActive)
        [self clearTintWithSecondsDelay:0.05];
}

#pragma mark - TintingPart

-(UIImage *)imageRepresentation
{

    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;    
}

-(UIImage*)imageRepresentationWithTintColor:(UIColor*)color
{
    UIImage* viewImage = [self imageRepresentation];
    viewImage = [self tintedImage:viewImage UsingColor:color];
    return viewImage;
}

-(UIImage *)tintedImage:(UIImage*)image UsingColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, [[UIScreen mainScreen] scale]);
    CGRect drawRect = CGRectMake(0, 0, image.size.width, image.size.height);
    [image drawInRect:drawRect];
    [tintColor set];
    UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceAtop);
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}


#pragma mark - Dynamic setters/getters for Associative References

-(void)setTintImageView:(UIImageView *)tintImageView
{
    objc_setAssociatedObject(self, tintImageViewKey, tintImageView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
}

-(UIImageView*)tintImageView
{
    return objc_getAssociatedObject(self , tintImageViewKey);
}


-(UIColor*)tintColor
{
    return  objc_getAssociatedObject(self , tintColorKey);
}

-(void)setTintColor:(UIColor *)tintColor
{
    objc_setAssociatedObject(self, tintColorKey, tintColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)tintOnTouchActive
{
    return [objc_getAssociatedObject(self, tintOnTouchActiveKey) boolValue];
}

-(void)setTintOnTouchActive:(BOOL)tintOnTouchActive
{
    objc_setAssociatedObject(self, tintOnTouchActiveKey, [NSNumber numberWithBool:tintOnTouchActive], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

关于objective-c - 用它的所有 subview 给 UIView 着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8389193/

有关objective-c - 用它的所有 subview 给 UIView 着色的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  3. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  4. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  5. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  6. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  7. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  8. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  9. ruby - 如何遍历 Ruby 中所有正则表达式匹配的字符串? - 2

    我们有一个字符串:“”这个正则表达式://i如何从当前字符串中获取所有匹配项? 最佳答案 "".scan(//)参见scan在ruby​​-docs上 关于ruby-如何遍历Ruby中所有正则表达式匹配的字符串?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6857852/

  10. ruby-on-rails - 在所有延迟的作业之前 Hook - 2

    是否可以在所有delayed_job任务之前运行一个方法?基本上,我们试图确保每个运行delayed_job的服务器都有我们代码的最新实例,所以我们想运行一个方法来在每个作业运行之前检查它。(我们已经有了“check”方法并在别处使用它。问题只是关于如何从delayed_job中调用它。) 最佳答案 现在有一种官方方法可以通过插件来做到这一点。这篇博文通过示例清楚地描述了如何执行此操作http://www.salsify.com/blog/delayed-jobs-callbacks-and-hooks-in-rails(本文中描述

随机推荐