iOS上下文实现评价星星示例代码

2025-05-29 0 15

常规思路:

创建两个 view,通过 for 循环创建 imageview,未点亮星星视图在下、点亮星星视图在上重合在一起,当用户点击视图时,通过改变点亮星星视图的 width 实现功能

本文思路:

直接重写 drawrect 方法,在 drawrect 用 drawimage 画出星星,根据 currentvalue 画出不同类型的星星,当用户点击视图时,改变 currentvalue,并根据改变后的 currentvalue 重新画出星星

展示图:

iOS上下文实现评价星星示例代码

代码:

自定义一个继承 uiview 的 cystarview

属性:

?

1

2

3

4

5

6

7

8

9

10

11

12
/** 完成后执行的block */

@property (copy, nonatomic) void(^completionblock)(nsinteger);

/** 是否可以点击 */

@property (assign, nonatomic) bool clickable;

/** 星星个数 */

@property (assign, nonatomic) nsinteger numberofstars;

/** 星星边长 */

@property (assign, nonatomic) cgfloat lengthofside;

/** 评价值 */

@property (assign, nonatomic) nsinteger currentvalue;

/** 星星间隔 */

@property (assign, nonatomic) cgfloat spacing;

重写 setter 方法,在 setter 方法中调用 setneedsdisplay,会执行 drawrect:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
- (void)setlengthofside:(cgfloat)lengthofside {

// 超过控件高度

if (lengthofside > self.frame.size.height) {

lengthofside = self.frame.size.height;

}

// 超过控件宽度

if (lengthofside > self.frame.size.width / _numberofstars) {

lengthofside = self.frame.size.width / _numberofstars;

}

_lengthofside = lengthofside;

_spacing = (self.frame.size.width - lengthofside * _numberofstars) / _numberofstars;

[self setneedsdisplay];

}

在 drawrect 中画星星

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
- (void)drawrect:(cgrect)rect {

uiimage *lightimage = [uiimage imagenamed:@"star_light"];

uiimage *darkimage = [uiimage imagenamed:@"star_dark"];

// 获取当前上下文

cgcontextref context = uigraphicsgetcurrentcontext();

for (int i = 0; i < self.numberofstars; i ++) {

// 根据 currentvalue 选择是画亮的还是暗的星星

uiimage *image = i >= self.currentvalue ? darkimage : lightimage;

cgrect imagerect = cgrectmake(self.spacing / 2 + (self.lengthofside + self.spacing) * i, (self.frame.size.height - self.lengthofside) / 2, self.lengthofside, self.lengthofside);

cgcontextsavegstate(context);

// 坐标系y轴是相反的,进行翻转

cgcontextscalectm(context, 1.0, - 1.0);

cgcontexttranslatectm(context, 0, - rect.origin.y * 2 - rect.size.height);

cgcontextdrawimage(context, imagerect, image.cgimage);

cgcontextrestoregstate(context);

}

}

使用:

在要使用的控制器中:

?

1

2

3

4

5

6

7

8

9

10
#import "cystarview.h"

// 初始化,传入必要参数

cystarview *starview = [[cystarview alloc] initwithframe:frame numberofstars:number lengthofside:length];

// 设置 clickable,评论界面设置为yes,展示界面设置为no

self.starview.clickable = yes;

//

// 设置 completionblock

self.starview.completionblock = ^(nsinteger currentvalue) {

// 点击后的操作放这里

};

项目地址:点我点我!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS上下文实现评价星星示例代码 https://www.kuaiidc.com/90546.html

相关文章

发表评论
暂无评论