先看效果,如果使用线程控制,树的颜色将会变化,使用的图片如果足够精致,效果将会更好。
图片中这棵树,不是背景图片,是自定义View+图片共同效果,借助上一篇的彩色效果,加上一颗树的图片即可完成,看代码吧,太晚了,不解释。
//
// MyMagicalView.h
// MyUIView
//
// Created by Moluth on 17/4/12.
// Copyright (c) 2017年 Moluth. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MyMagicalView : UIView{
@public double tr,tg,tb;
@public void* imageData;
@public int width,height;
}
@end
//
// MyMagicalView.m
// MyUIView
//
// Created by Moluth on 17/4/12.
// Copyright (c) 2017年 Moluth. All rights reserved.
//
#import "MyMagicalView.h"
@implementation MyMagicalView
- (id)initWithFrame : (CGRect)frame
{
self = [super initWithFrame:frame];
UIImage *img=[UIImage imageNamed:@"tree.jpg"];
[self getImageData:img];
return self;
}
-(void)drawRect:(CGRect)rect{
// 获取图形绘制上下文
int xa=round(rect.origin.x);
int xb=round(rect.origin.x+rect.size.width);
int ya=round(rect.origin.y);
int yb=round(rect.origin.y+rect.size.height);
unsigned char* data=(unsigned char*)imageData;
CGContextRef context = UIGraphicsGetCurrentContext();
double r,g,b;
for(int x=xa;x<xb;x++){
for(int y=ya;y<yb;y++){
int c=data[((height-y)*width+x)*4+1];
if(c>235)continue;
r=(sin(x*0.0017-y*0.0005+tr+34.1)+1.0)/2.0;
g=(sin((xb-x)*0.0009+y*0.0015+tg)+1.0)/2.0;
b=(sin(x*0.0047+(yb-y)*0.0001+tb)+1.0)/2.0;
CGContextSetRGBFillColor (context, r, g, b, 1.0);//设置填充颜色
CGContextFillRect(context,CGRectMake(x, y, 1, 1));
}
}
}
- (void)getImageData:(UIImage*)image
{
width=image.size.width;
height=image.size.height;
if (imageData == NULL)
imageData = malloc(4 * image.size.width * image.size.height);
CGColorSpaceRef cref = CGColorSpaceCreateDeviceRGB();
CGContextRef gc = CGBitmapContextCreate(imageData,
image.size.width,image.size.height,
8,image.size.width*4,
cref,kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(cref);
UIGraphicsPushContext(gc);
[image drawAtPoint:CGPointMake(0.0f, 0.0f)];
UIGraphicsPopContext();
CGContextRelease(gc);
}
@end
///今天到此为止了,结束,bye