今天学了简单的二维码生成,就是把输入的文字或者网址点击生成按钮后生成为二维码。
有关生成二维码就一个方法可以了
- (UIImage *)createQRCodeWithStr:(NSString *)str
{
CIFilter * filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setDefaults];
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];
CIImage * outPutImage = [filter outputImage];
return [UIImage imageWithCIImage:outPutImage];
}
全部代码:
//
// ViewController.m
// try
//
// Created by 颜玥 on 14/12/26.
// Copyright (c) 2014年 颜玥. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{
UITextField* tf;
UIImageView * img;
}
@end
@implementation ViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (!self) {
self.view.backgroundColor = [UIColor whiteColor];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configView];
}
- (void)configView
{
tf = [[UITextField alloc]initWithFrame:CGRectMake(10, 150, 300, 100)];
[tf setPlaceholder:@"请输入你想显示的文字或者网址~"];
tf.borderStyle = UITextBorderStyleRoundedRect;
[tf setBackgroundColor:[UIColor yellowColor]];
[self.view addSubview:tf];
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 20)];
[btn setBackgroundColor:[UIColor grayColor]];
[btn setTitle:@"生成二维码" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(click_btn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
img = [[UIImageView alloc]initWithFrame:CGRectMake(100, 350, 100, 100)];
img.image = [UIImage imageNamed:@"{tx"];
[self.view addSubview:img];
}
- (UIImage *)createQRCodeWithStr:(NSString *)str
{
CIFilter * filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setDefaults];
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKey:@"inputMessage"];
CIImage * outPutImage = [filter outputImage];
return [UIImage imageWithCIImage:outPutImage];
}
- (void)click_btn:(UIButton *)sender
{
img.image = [self createQRCodeWithStr:tf.text];
[tf resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end