本文实例为大家分享了ios自定义滑杆的具体代码,供大家参考,具体内容如下
先让我们看看效果:
主要实现的代码:
uiimage *thumbwithlevel(float alevel) { float inset_amt = 1.5f; cgrect baserect = cgrectmake(0, 0, 40, 100); cgrect thumbrect = cgrectmake(0, 40, 40, 20); uigraphicsbeginimagecontext(baserect.size); cgcontextref context = uigraphicsgetcurrentcontext(); [[uicolor darkgraycolor] setfill]; cgcontextaddrect(context, cgrectinset(thumbrect, inset_amt, inset_amt)); cgcontextfillpath(context); [[uicolor whitecolor] setstroke]; cgcontextsetlinewidth(context, 2); cgcontextaddrect(context, cgrectinset(thumbrect, 2 * inset_amt, 2 * inset_amt)); cgrect ellipserect = cgrectmake(0, 0, 40, 40); [[uicolor colorwithwhite:alevel alpha:1] setfill]; cgcontextaddellipseinrect(context, ellipserect); cgcontextfillpath(context); nsstring *numstring = [nsstring stringwithformat:@"%0.2f",alevel]; uicolor *textcolor = (alevel > 0.5) ? [uicolor blackcolor] : [uicolor whitecolor]; uifont *font = [uifont fontwithname:@"georgia" size:15]; nsmutableparagraphstyle *style = [[nsmutableparagraphstyle alloc] init]; style.linebreakmode = nslinebreakbycharwrapping; style.alignment = nstextalignmentcenter; nsdictionary *attr = @{nsfontattributename:font,nsparagraphstyleattributename:style,nsforegroundcolorattributename:textcolor}; [numstring drawinrect:cgrectinset(ellipserect, 0, 6) withattributes:attr]; [[uicolor graycolor] setstroke]; cgcontextsetlinewidth(context, 3); cgcontextaddellipseinrect(context, cgrectinset(ellipserect, 2, 2)); cgcontextstrokepath(context); uiimage *theimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext(); return theimage; }
在这里我们通过context的方法将图片画出了,对于性能有点要求,但是现在应该不在乎这点性能了
- (void)updatethumb { if ((self.value < 0.98) && (abs(self.value - previousvalue) < 0.1f)) { return; } uiimage *customimg = thumbwithlevel(self.value); [self setthumbimage:customimg forstate:uicontrolstatehighlighted]; previousvalue = self.value; }
通过滑块的值来使上面的值进行变化,更加的直观
[self setthumbimage:simplethumb() forstate:uicontrolstatenormal]; [self addtarget:self action:@selector(startdrag:) forcontrolevents:uicontroleventtouchdown]; [self addtarget:self action:@selector(updatethumb) forcontrolevents:uicontroleventvaluechanged]; [self addtarget:self action:@selector(enddrag:) forcontrolevents:uicontroleventtouchupoutside | uicontroleventtouchupinside];
对于不同的状态来进行不同的操作,让滑杆的用户体验度更加的完整
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。