中文版b4a新手指南-第14-15章语言画图_第1页
中文版b4a新手指南-第14-15章语言画图_第2页
中文版b4a新手指南-第14-15章语言画图_第3页
中文版b4a新手指南-第14-15章语言画图_第4页
中文版b4a新手指南-第14-15章语言画图_第5页
已阅读5页,还剩55页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Getting Trial InstallingBasic4AndroidandAndroid Installandconfigure InstallingAndroid Myprogram(My Secondprogram The andToolbar Code Undo– Collapsea Collapsea Collapsethewhole Builtin Jumptoa Highlightingoccurrencesof Moduleandsubroutinelists Screensizesand Specialfunctionslike50%x, PerXToCurrent,PerYToCurrent- DipToCurrent- Workingwithdifferentscreensizes/numberof Screen Supportingmultiplesceens-tipsandbest Howtochangetheviewssizeandtextsize? The Launchan Createanew Emulator Process Exchangingfileswiththe ConnectingarealdeviceUSB/B4A youneedtoinstallB4A-Bridgeonyourdevice RunB4A-Bridgeonyour ConnecttheIDEtothe The The Generate BringTo SendTo DuplicateSelected RemoveSelected Change Connectdeviceor General Image Properties Layout Select Addingviewsby Designer SimpleAutoScaleexamplewithonlyonelayout SameAutoScaleexamplewithportraitandlansdsclayout AutoScalemoreadvanced UI ProcessandActivitylife Howdowehandleit Processglobal Activity SubActivity_Create(TimeAs Globalsversus SubActivity_ResumeSubActivity_Pause(UserClosedAs Activity.Finish/ Variablesand Variable Namesof Declaring Simple Array Arrayofviews Type Process Activity Activity Class Code Service Searchfunctioninthe TheB4Aation Example User example(UserInterface.b4a) TabHostexample Buttontoolboxexample Programwith3Activities Basic Program Activity_Create(TimeAsBoolean) Activity_Pause(UserClosedAsBoolean) Boolean If–Then–End Select– Loop For– For- Do- Callinga CallingaSubfromanother Returned Standard Additionallibraries Errormessage"Areyoumissingalibrary String File Text Graphics/ Drawingtest steps Drawingrotatingbitmaps/ Simpledraw VB6versus "Pleasesaveproject" "Areyoumissingalibraryreference" Howloading/updatinga Whendoweneedto'Initialize'andwhen Splitalonglineintotwoormore Avoidclosinganapplication/capturekeycodeslikeBack/UnwantedeventslikeClick,Touchor Adding removeaViewwiththe "Processhastimeout" Gettingapicturefromthe Howtodeletex.balfilesorotherfilesfroma Blockascreen Closesecond Takingascreenshot Aftercompiling,wherearethe Runanapplicationfromanother HowtopassanArraytoa Gettinglanguageandcountryfrom Whereistheapk Whyismyapkfilename Whyismyapkfilename SelectTrue/Case Fillanarraywithrandomnumberswithout Detectscreen Somefunctionsdon'tworkin Callingtheinternal GettheAlpha/Red/Green/ Getdevice GenerateaClick "Outofmemory"Error/ Removethescrollbarfroma Checkifdirectory SetFullScreenin ChangeEditTextinput Sortingafilelistaccordingtolastmodified Getthedpivaluesofthedevice(dotsper Findingjavaprogram MaincontributorsErelUziel KlausChristl(klaus)TosearchforagivenwordorsentenceusetheSearchfunctioninthe Allthesourcecodeandfilesneeded(layouts,imagesetc)oftheexampleprojectsinthisguideareincludedintheSourceCodefolder.AmoreadvancedguidecanbedownloadedUser'sBasic语 在计算机语言中,BASIC(英文全称:Beginner'sAll-purposeSymbolicInstructionCode)是简单易用的高级编程语言的一种。BASIC语言1964年由Dartmouth学院(位于的新罕布什尔州NewHampshire,USA)的JohnGe eKemeny和ThomasEugeneKurtz二人创立。那是主要用于微软的VB(VisualBasic).程序 ProcessandActivitylife'Activitymodule'Activity模块Sub'Theseglobalvariableswillbedeclaredoncewhentheapplicationstarts.'Thesevariablescanbeaccessedfromallmodules.'应用启动是一些全局变量在这里EndSubSubGlobals'Theseglobalvariableswillberedeclaredeachtimetheactivityis'Thesevariablescanonlybeaccessedfromthismodule.'这里的的全局变量在Activity创建时。EndSubActivity_Create( TimeAsBoolean)EndSubSubActivity_ResumeEndSubSubActivity_Pause(UserClosedAsEndProcess_Globals程序 这里的全局变量在整个程序的生命周期中都有效,可在任何整个程序的任何地方存.2Globals这里Activity的全局变量。在Activity的生命周期中有效,只能在本Activity内存取14.1.314.1.3Activity_Create TimeAsBoolean)程序如果变量和对象只初始化一次,可以用参数TimeSubActivity_Create( TimeAsBoolean)IfTime=TrueThenEndIfEnd14.1.414.1.4Activity_ResumeactivityActivity设置Subet_main.TextfilterEnd14.1.514.1.5Activity_PauseUserClosedAsBoolean)程序当activity这里你需要保存activity参数,这些参数当activityActivityActivityActivity_Resume,正常情况是触发Globals,Activity_CreateandActivity_Resume.UserclosedSubActivity_Pause(UserClosedAsBoolean)camEx.Release'相机控制gps130.Stop'停止Gps控制End程序流:例子:

Sub,它会返回到调用25行执行btnAction表达 例如:2+3是一个算术表达式计算结果是5。表示式里的变量指向此变量的内存地址,比如y+6是一个表达式。4=4True。数学表达 +x+3加-x-3减*x*2乘/x/2除xMod2Power(x,y)1幂优先级:在一个表达式里,1234+5*3+2= >4+15+(4+5)*(3+2)= >9*(4+5)2*(3+2)= >92* >81*11Mod4= >Modistheremainderof10/ >23atthepowerof-22=-(-2)2=关系表达 B4ATrueFalse=x=x<>>x><x<x>=x<=布尔表达 或ZXOrYZTrueXYTrue与ZXAndYZTrueXYNot(非X= Y=Not(X)那么Y=XYZZ条件语 BasicIf–Then–End Iftest1Then'code1ElseIftest2Then'code2'code3EndIf当执行到If关键字时test1test1Truecode1ElseIf。EndIf。test1Falsetest2test2Truecode2Else。EndIf。test2Falsecode3EndIf2True另一些例子Ifb=0a EndIfb0Thena Ifb=0a a=1EndIfIfb0Thena0Elsea 同一行的写法备注:B4AVB Else Ifb=0Thena=0:c=B4AVB有很大的不同。 Ifb=0 Ifb=0a= a=End c=c= EndB4ACarriageReturnCRSelect–Case分支语 也有叫开关语句的,检测TestExpression的值,根据不同的Expressions执行不同的分支常规用法Select TestExpression检测表达式Case' ExpressionList1表达式Case ' ExpressionList2另一个Case 'code3EndSelectSelectCase结构执行顺序先计算TestExpression的值TestExpression的值ExpressionList1EndSelectTestExpression的值ExpressionList2EndSelectTestExpression则执EndSelectSelectCase123 Selecta TestExpressionabCase12,Select TestExpressionCase"A","B",SubActivity_Touch(ActionAsInt,XAsFloat,YAsFloat)SelectActionCaseActivity.ACTION_DOWNCaseActivity.ACTION_MOVECaseActivity.ACTION_UPEndSelectEndSub注释:B4AVB SelectValue SelectCaseValueCase1,2,3,4,8,9,10 Case1To4,8To9VBCase1To4B4A循环语句 BasicFor– For–Next循环用于知道循环次数的情况。Forin1Ton2Step n1Specific n2n3i=n1ForNextspecificcodeNextin3.i=i+n3.检查iYes,继续执行循环体For到Next。No,Next下面的语句.如果步长是+1可以省略。Fori=0To Fori=0To10Step Fori=n3To0Step-1ExitForNext循环Fori0To A'IfA0Then 'codeContinue可以短路循Fori0To A'codeIfA0ThenContinuecode2'code2:B4AVB VBNext ExitVB循环变量增加在Next后面Exit后还有For- Basic4Android2.2及以后的版本引进。For-Next循环的变体。范例ForEachnAsTypeIn nSpecific For–Each循环的执行顺序开始nn=ForNextspecificcodeNextnNonn=YesNextFor-Each的例子DimNumbers()AsIntDimSumAsIntNumbers=ArrayAsInt(1,3,5,2,9)Sum=0ForEachnAsIntInNumbersSum=Sum+nForNext循环DimNumbers()AsIntDimSumAsIntDimiAsNumbers=ArrayAsInt(1,3,5,2,9)Sum=0Fori=0ToNumbers.Length-1Sum=Sum+Numbers(i)ForEach的强大ForEachlblAsLabelInActivitylbl.TextSize=20For-Next循环Fori=0ToActivity.NumberOfViews-1DimvAsViewv=Activity.GetView(i)IfvIsLabelThenDimlblAsLabellbl=vlbl.TextSize=20EndIfDo- Do–Loop2DoWhile test testTrue执行DoUntil test任何表达 codetestDoWhileLoop开始testTrueFalseLoopDoUntilLoop执行顺序开始testFalseTrueLoopDoWhiletest'codeIfa0Then a=0'codeDoUntilLoopDimi,nAsi=DoUntili=10'codei=i+1DoWhileLoopDimi,nAsi=DoWhilei<10'codei=i+1textList对象:DimlstTextAsListDimlineAsStringDimtrAsTextReaderline=tr.ReadLineDoWhileline<>Nullline=tr.ReadLine注释:B4AVB ExitVBExit后面多了VB里还有下面两种循环B4A ' 'LoopWhile LoopUntil SubBasci4Android的代码Subsubs。代码是按顺序执Sub Declaring Sub用下面的方法SubCalcInterest(CapitalAsDouble,RateAsDouble)AsDoubleReturnCapital*Rate/100EndEndSubs的总是在模块级,不能在一个Sub中另一个Sub调用一个 sub的名字来调用一Interest=CalcInterest(1234, sub Sub 从另一模块调用 在code模块你的sub可以在任何其他模块里调用,但必须加code模块名前缀范例:如果CalcInterest在MyModule里,然后调用它必须这样Interest=MyModule.CalcInterest(1234,Interest=CalcInterest(1234,Su 总体来说,你可以用任何合法的名字给sub命名。建议用有一定意义名,象例子中CalcInterest,这样你可以大概知道这个sub能干什么Sub2个subSubCalcInterest(CapitalAsDouble,RateAsDouble)AsDoubleReturnCapital*Rate/100EndSub的参 Subsub名称的后面,参数表放在括号里。参数类型直接在参数表中。SubCalcInterest(CapitalAsDouble,RateAsDouble)AsDoubleReturnCapital*Rate/100EndSub的返回 Sub可以有返回值,返回值可以是任何对象。Return关键字。SubCalcInterest(CapitalAsDouble,RateAsDouble)AsDoubleReturnCapital*Rate/100End事件 在面象的程序中,的对象可以用事件驱动。最常用的事件 View时触发SubButton1_Click'YourcodeEnd View时触发SubButton1_LongClick'YourcodeEndTouch(ActionAsInt,XAsFloat,YAs3种动作Activity.Action_DOWN,用户用手指按屏幕 XYActivityTouch事件SubActivity_Touch(ActionAsInt,XAsFloat,YAsFloat)SelectActionCase'YourcodeforDOWNactionCaseActivity.ACTION_MOVE'YourcodeforMOVEactionCaseActivity.ACTION_UP'YourcodeforUPactionEndSelectEndCheckChanged(CheckedAsBoolean)CheckBoxRadioButton触发。CheckedTrue未勾选为False。范例SubCheckBox1_CheckedChange(CheckedAsIfChecked=True'Yourcodeifchecked'YourcodeifnotcheckedEndIfEndKeyPress(KeyCodeAsInt)As,False,范例SubActivity_KeyPress(KeyCodeAsInt)AsBooleanDimAnswAsIntDimTxtAsIfKeyCode=KeyCodes.KEYCODE_BACKThen'ChecksifKeyCodeisBackKeyTxt="Doyoureallywanttoquittheprogram?"Answ=Msgbox2(Txt,"ATTENTION","Yes","","No",Null)'MessageBoxIfAnsw=DialogResponse.POSITIVEThen'IfreturnvalueisYesthenReturnFalse 'Return=FalsetheEventwillnotbeconsumed weleavetheprogramReturnTrue 'Return=True theEventwillbeconsumedtoavoidEndIf leavingtheprogramEndIfEndSub库irres B4A的库可以包含很多对象和函数。B4A另,AndrewGraham(agraham)是经常开发库的用户,用户可以库增补到LibTab对于附加库检查是否是的版本IDELibTab标准 B4AB4AC:\ProgramFiles\Anywhere附加库文件 D:\Basic4Android\AddLibraries当你安装新版本的B4A,所有的标准库会自动更新,但不包括附加库。这样的好处就是你的附加库你不用关心,安装新版本的B4A附加库不受影响。如果你安装附加库文件夹,你必须在IDE里配置它的路径。Tools/ConfigurePaths:输入文件夹后点.按钮就行了错误信息"Areyoumissingalibrary 如果你看到了这个错误信息,意味着你忘记在LibTab里勾选库字符串操 字符串替换范例txt=txt=txt.Replace(",",结果字符串操控函数列表 TrueSearchFor True如果后缀是SuffixEqualsIgnoreCase(Other)True如果字符串等于Other , SearchFor从index SearchFor Replace(, 返回被Replacement替换的新字符串 True如果字符串的前缀是 BeginIndexSubstring2(BeginIndex,EndIndex)BeginIndexEndindex NumberFormat(NumberAsDouble,MinimumIntegersAs umFractionsAsNumberFormat(12345.6789,0,2)=NumberFormat(1,3,0) =001NumberFormat(Value,3,0) variablescanbeused.NumberFormat(Value+10,3,0)arithmeticoperationscanbeused.NumberFormat((lblscore.Text+10),0,0)ifonevariableisastringaddNumberFormat2(NumberAsDouble,MinimumIntegersAsInt, umFractionsAsInt,MinimumFractionsAsInt,GrouUsedAsBoolean)NumberFormat2(12345.67,0,3,3,True) =12,345.670定时对象 TimerticktimerUI线程的其注意

TimerUI线程忙的时候不会触发(Timer时间在Activity是Paused是不会被触发,比如一个交互框可见时三个参数 初始化EventName和interval参数Timer1.Initialize(EventNameAsString,IntervalAsLong) Timer1.Initialize("Timer1",1000) Timer1.Interval= Timer1.Interval=1000,1 Timer Timer1.Enabled= TheTickroutineiscalledeverytimeinterval. SubTimer1_TickTimer必须在Process_Global里SubProcess_GlobalsDimTimer1AsTimerTimer还必须在Activity_Create初始化SubActivity_Create( TimeAsBoolean)IfTime=TrueThenTimer1.Initialize("Timer1",1000)EndIfTimerTickSubTimer1_Tick'DosomethingEndRotatingNeedle.文件 文件对象File 预定义的文件对象file有很多功能–IDEFiles下的文件。你不能在这个文件夹创建新文件(apk文件)。File.DirInternal/这两个文件夹在设备的主器和应用程序。缓存文件夹可能作系统删除如果系统需要的空间卡的 SD这个文件夹是:<storage注意,调用上面的两个文件夹将需要添加您的应用程序external_storage。建议:你可以检查是否有卡,及卡是否可用。检查一个文件时候存在可用File.Exists(DirAsString,FileNameAs文件对File包括一些读写文件的方法。File.OpenOutput(DirAsString,FileNameAsString,AppendAs,File.OpenInput(DirAsString,FileNameAs为文件打File.WriteString(DirAsString,FileNameAsString,TextAsFile.ReadString(DirAsString,FileNameAsString)AsFile.Wriist(DirAsString,FileNameAsString,ListAs写List的所有值到一个文件,所有的值都转换为字符串,每个值在单独的一行。注意,如果list的值里有换行符,将会分成多行,当你再时变成多个项目。File.ReadList(DirAsString,FileNameAsString)AsFile.WriteMap(DirAsString,FileNameAsString,MMpertiesWikipediathefreemap为一个设置文件。File.ReadMap(DirAsString,FileNameAsString)AsMapFile.Copy(DirSourceAsString,FileSourceAsString,DirAsString,FileAsAssetsFile.Delete(DirAsString,FileNameAsFile.ListFiles(DirAsString)Aslist。DimList1AsList1=List1可以在SubGlobals里File.Size(DirAsString,FileNameAsassets文件命名 Androida-z,AZ,09_*不允许。:MyFile.txtMyFile.txt和myfile.txt子 Subfodes 安卓上你可以创建自己的 ImageView1.Bitmap=LoadBitmap(File.DirInternal&"/Pictures", 和文件名之间也需要"/"分ImageView1.Bitmap=LoadBitmap(File.DirInternal,写文本文件对象 这里有两个常用的文件文件操控对象:TextWriter-outputstreamTextWriter范例DimWriterAsTextWriterWriter.Initialize(File.OpenOutput(File.DirRootExternal,"Test.txt",False))Writer可以在SubGlobals里TextWriter.Initialize2(OutputStreamAsOutputStream,EncodingAs-outputstreamTextWriterEncodingCodePageCharacterSet(见下一章)范例DimWriterAsWriter.Initialize2(File.OpenOutput(File.DirRootExternal,"Test.txt",False),"ISO-8859-Writer可以在SubGlobals里TextWriter.Write(TextAsTextWriter.Wriine(TextAsTextLFChr(10)TextWriter.Wriist(ListAsCRLF2(ReadList2个项目)。DimWriterAsTextWriter ine("Thisistheline") ine("Thisisthesecondline")14.10.5读14.10.5读文本文件对象 这里有两个常用的文件文件操控对象:TextWriterDimReaderTextReaderReader可在SubGlobals里TextReader.Initialize2(InputStreamAsInputStream,EncodingAs范例DimReaderReader可以在SubGlobals里范例txt=TextReader.ReadLineAsThenewlinecharactersarenotDimReaderAsTextReaderDimlineAsStringline=Reader.ReadLineDoWhileline<>Nullline=Reader.ReadLineList对象。范例List1=14.10.6文本编码Text 字符表、代码页都是一个意思,可以互换替代。UTF-8WindowsASCII和ASCII128个字符33256个字符包含ASCII128个字符。在西方国家许多文件由windows程序生成,用的是ANSI字符集。例如:Excelcsv文件,记事本文件 UTF-UTF-16UTF-US- ASCIIISO-8859-1ANSIANSIwindowsWindows-1252字符集。如果你Windows用的文件也用Windows-1252字符集。WindowsAndroidAndroid,LFLineFeed)Chr(10)Windows有CRCarriageReturnChr(13LFChr(102个字符为行结束。如果你好写Windows用的文件要自己加CR字符。 Chr(13)&TextReaderTextWriterInitialize2CSVExcelcsv文件小建议csv另存UTF-8编码文Notepad+UTF-8或读整个文件用TextReader.Initialize2方法,编码用"Windows-1252"TextWriter.InitializeLoadCSVLoadCSV2见StringUtils库DimtxtAsStringDimtrAsTextReadertxt=tr.ReadAllDimtwAslstTest=StrUtil.LoadCSV2(File.DirInternal,"TestCSV1_W.csv",";",BOM(ByteOrderUTF-8Windows-1252编码的文本编辑器或Web浏览器会显示Notepad++NotePadUTF-8BOM另一个转换Windows-1252UTF-8的方法见下面代Dimvar,resultAsStringvar="Gestió"DimarrByte()AsarrByte=var.GetBytes("Windows-result=BytesToString(arrByte,0, ength, Lists类似动态数组ListLists很常用,很多的例程都 LoadCSV,DBUtils模块 ExecuistView,ExecuteHtml,ExecuteJSONCharts模 保存变list List.DimList1AsListList1.AddAll(ArrayAsInt(1,2,3,4,list1:DimList1AsList1.Initialize2(ArrayAsInt(1,2,3,4,DimList1AsDimSomeArray(10)AsString'FillthearrayAdd(itemAslistAddAllArrayAsString("value1value2"))list的最后增加数组的所有值。List1.AddAll(ArrayAsInt(1,2,3,4,AddAllAt(IndexAsIntListAsList)在index位置数组所有元素。List1.AddAll(12,List2)List1.AddAllAt(12,ArrayAsInt(1,2,3,4,InsertAt(IndexAsInt,ItemAs在index位置itemAsaresultallitemswithindexlargerthenthespecifiedindexareRemoveAt(IndexAsInt)List可以任何对象,但需要在processglobal你,这里的对象不包括Activity对List的尺寸Get(IndexAsnumber=For-looplist的所有值Fori=0ToList1.Size-1DimnumberAsIntnumber=List1.Get(i) ist(DirAsString,FileNameAsString,ListAs File.ReadList(DirAsString,FileNameAsList1=File.ReadList(File.DirRootExternal,List1.Set(IndexAsInt,ItemAsList1.Set(12,List可以排序(所有项目都是数值或字符):Sort(AscendingAsBoolean) sortascending sortSortCaseInsensitive(AscendingAsList Map是一个内存中键和值的集合对象,所有函数的详细描述见Map章节。Map对应用设置非常有用, 用于设置Map Map.DimMap1AsMap增加一个新元素Put(KeyAsObject,ValueAsGet(KeyAsLanguage=取指定位置的键或值GetKeyAtGetValueAt可以遍历所有项目。GetKeyAt(IndexAsKey=GetValueAt(IndexAsValue=ContainsKey(KeyAsIfMap1.ContainsKey("Language")Msgbox("Thereisalreadyanentrywiththiskey!","ATTENTION")EndRemove(KeyAs File.WriteMap(DirAsString,FileNameAsString,MMap)File.WriteMap(File.DirInternal,"settings.txt",mapSettings)Map保存为文件ReadMap(DirAsString,FileNameAsmapmapSettings=File.ReadMap(File.DirInternal,File.ReadMap2(DirAsString,FileNameAsString,MReadMap.ReadMap2增加了一个map参数。ReadMap2可以按map需要强制排序。图/画Graphics/ 概 Canvas画布对象。Canvascanvsa画布初始化时,会创建一个新的位图,此位图的背景就是它所在视图的背景,意CanvasInvalidate方法刷新它。Canvas画布可以临时限定在指定区域(只影响这个区域)ClipPath方法RemoveClip方法。Canvas这是一个antivity对象,不能在SubProcess_Globals下CanvasBitmapBitmap1as x,yx1,y1,x2,y2As Coloras SrcRectDestRactRect1As 矩形RectFilledAs (True用的最多的绘图函数DrawBitmap(Bitmap1AsBitmap, Rect, Bitmap1SrcRect源矩形,DestRect目标矩形DestRect和SrcRectDrawBitmapRotated(Bitmap1AsBitmap,SrcRe Rect,DestRe Rect,DegreesAsFloat)DrawCircle(xAsFloat,yAsFloat,RadiusAsFloat,ColorasInt,FilledAsBoolean,StrokeWidthAsFloat)xyRadiusDrawColor(ColorAsColorsDrawLine(x1AsFloat,y1AsFloat,x2AsFloat,y2AsFloat,ColorasInt,StrokeWidthAsFloat)DrawRect(Rect1AsRect,ColorAsInt,FilledAsBoolean,StrokeWidthasDrawRectRotated(Rect1AsRect,ColorAsInt,FilledAsBoolean,StrokeWidthAsFloat,DegreesAsFloat)DrawText(TextAsString,xAsFloat,yAsFloat,Typeface1AsTypeFace,TestSizeAsFloat,ColorAsIntAlign1AsAlign)DrawTextRotated(TextAsString,xAsFloat,yAsFloat,Typeface1AsTypeFace,TestSizeAsFloat,ColorAsIntAlign1AsAlign,DegreesAsFloat)画旋转文本画图测试程 第一 此例程在:SourceCode\Graphics\RotatingNeedle\GraphicsCanvasCanvas画位图.通常在这几个视图上画:Activity,Panel,ImageViewBitmap.Canvas2个初始化方法。 Canvas在例程中,用了几个画图函数在Activity和Panel上画了几个图形,panel在布局文main2CanvasIntheexampleprogramwe'lluseseveraldrawingfunctionsanddrawontotheActivityandapnlGraphdefinedinthe'main'layoutfile.Hereweneedtwo 开 和初始首先须视图和对象,需要PanelSubDimpnlGraphAsDimcvsActivity,cvsGraphAsCanvasEndSub然后须加载布局文件,初始化SubActivity_Create( TimeAsBoolean)'加载布局文件'activityCanvas'panel初始化CanvasEnd 划Activity_ResumeActivity上画横线:DrawLine(x1AsFloat,y1AsFloat,x2AsFloat,y2AsFloat,ColorasInt,StrokeWidthAsFloat)Where:x1,y1x2,y2StrokeWidth线宽:在ActivitycvsActivity.DrawLine(20dip,20dip,160dip,20dip,Colors.Red,然后pnlGraph上画横:坐标是相对于视图的左上角,Panel在pnlGraphcvsGraph.DrawLine(20dip,20dip,160dip,20dip,Colors.Red,画矩画矩Activity上画一个空的矩形函数用DrawRect(Rect1AsRect,ColorAsInt,FilledAsBoolean,StrokeWidthasFloat)Where:Filled:False只画边框TrueRect.要在ActivityRectDimrect1Asrect1.Initialize(20dip,40dip,150dip,100dip)cvsActivity.DrawRect(rect1,Colors.Blue,False,3dip)接下来同样的Rect对象画在pnlGraph:在pnlGraphcvsGraph.DrawRect(rect1,Colors.Blue,True,画画Activity上画一个空心圆DrawCircle(xAsFloat,yAsFloat,RadiusAsFloat,ColorasInt,FilledAsBoolean,StrokeWidthAsFloat)Wherex,yRadiusFilled:FalseTrueStrokeWidthFilledTrue无关在ActivitycvsActivity.DrawCircle(220dip,70dip,30dip,Colors.Green,False,panel上画一个填充颜色的圆.因此可以先画一个填充圆,再画一个边框圆。在pnlGraphDimcenterX,centerY,radiusAsFloatcenterX=220dipcenterY=70dipradius=30dipcvsGraph.DrawCircle(centerX,centerY,radius,Colors.Green,True,3dip)cvsGraph.DrawCircle(centerX,centerY,radius,Colors.Red,False,3dip)画文画文:DrawText(TextAsString,xAsFloat,yAsFloat,Typeface1AsTypeFace,TestSizeAsFloat,ColorAsIntAlign1AsAlign)TextTypeFace1TextSizeisdip:"LEFT"CENTER"ActivitycvsActivity.DrawText("Testtext",20dip,150dip,Typeface.DEFAULT,20,_Colors.Yellow,"LEFT")pnlGraph上画旋转的文本3个变量:refX和 基点坐 DimrefX,refY,hlAsFloatrefX=150diprefY=180diphl=5dip在pnlGraphcvsGraph.DrawTextRotated("Testtext",refX,refY,Typeface.DEFAULT,_20,Colors.Black,"RIGHT",45)在文本的坐标基点上画个+cvsGraph.DrawLine(refX-hl,refY,refX+hl,refY,Colors.Red,1dip)cvsGraph.DrawLine(refX,refY-hl,refX,refY+hl,Colors.Red,画旋转位图/旋转指 :在第一个例程里介绍了DrawBitmapRotated函数.2个模式3ooo

2如果有这样的指针,需要做些计算才能使指针旋转为避免计算,要这样的指针,只要旋转位图,指针就是旋转效果。SubDimAngleStepAs 步进角度DimAngleAsFloat :Angle=-AngleStepDimModeAsBoolean :Mode=TrueDimTimer1AsTimerEndSub False=SubDimbtnGoStop,btnStep,btnModeAsButton pass,csvNeedleAsCanvas pass,bmpNeedleAsBitmap pass,imvNeedleAsImageView pass,SRectNeedle,DRectNeedleAsRectEndSub32个位图3个矩形,一个罗盘,2个指针(源和目标Activity_Create的代码:SubActivity_Create( TimeAsBoolean)Dimx,yAsFloat2pass.Bitmap= ImageViewx=(100%x- pass.Width)/2y=(100%y- pass.Height)/2 pass,x,y, Activity.AddView(imvNeedle,x,y, pass.Initialize(0, 和罗盘ImageView尺寸相ImageViewCanvasx=( pass.Width-bmpNeedle.Width)/2y=( pass.Height-bmpNeedle.Height)/2SRectNeedle.Initialize(0,0,bmpNeedle.Width,bmpNeedle.Height)DRectNeedle.Initialize(x,y,x+bmpNeedle.Width,y+bmpNeedle.Height)ImageViewCanvas初始化指针矩形(源和目标Endtimer200毫秒Timer1_TickSubDimAngle1AsAngle1=Angle=(Angle+AngleStep)Mod360IfMode=TrueThen EndIfEndSub

用ModModeTrue旋转指针ImageView用以更新ModeFalse,旋转罗盘用新角度画罗盘,ImageViewSubbtnStep_ClickEndSubIfTimer1.Enabled=TrueThenTimer1.Enabled=FalsebtnGoStop.Text="Go"btnStep.Visible=TrueTimer1.Enabled=TruebtnGoStop.TExt="Stop"btnStep.Visible=EndIfEndSubTimer1TruetimerTimer1FalsetimerTimer1.EnabledTruebtnStepSubbtnMode_ClickMode=Not(Mode)IfMode=TrueThenbtnMode.Text="Needleturns"csvNeedle.DrawRect(DRectNeedle,Colors.Transparent,True,1) btnMode.Text="Compassturns"csvNeedle.DrawBitmap(bmpNeedle,SRectNeedle,DRectNeedle)EndAngle=Angle-AngleStepEndModeNOTTureFalse,FalseModeTrue旋转指针设置按钮文本"NeedleModeFalse,简单画图函 SourceCode\Graphics\SimpleDrawFunctions\SimpleDrawFunctions.b4a3panelToggleButton你可以通 作看到不同图层的显示和隐藏组合效果activity用ToggleButtons按钮可显示或隐藏不同的图Panel是灰色背景:一个透明的圆activity的背景在圆中显示出一个半透明矩形activityLayer(0)图层上,触摸屏幕并移动,蓝色的透也是透明背景你可以通 作看到不同图层的显示和隐藏组合效果代码分析在SubGlobalsroutine视图和变量:SubDimpnlLayer(3)AsPanelDimcvsLayer(3)AsCanvasDimbtnLayer(3)AsToggleButtonDimrect1AsRectDimbmpBackgroundAsDimbdwBackgroundAsDimxc,yc,x1,y1,x2,y2,r1,r2,h,wAsFloatEndSub3Canva1Bitmap位图activity注意这里用数组了三个panel、canvas、DimpnlLayer(3AsPanelDimpnlLayer0pnlLayer1pnlLayer2AsSubActivity_Create( TimeAsBoolean)DimiAsInt TimeThenActivity.Background= Time=True初始化视加载Rose2.jpg文件到x1=2%xw=y1=100%y-55diph=50dipFori=0To2pnlLayer(i).Initialize("pnlLayer"&i)Activity.AddView(pnlLayer(i),0,0,100%x,85%y)pnlLayer(i).Tag=ix2=x1+i*33%xActivity.AddView(btnLayer(i),x2,y1,w,h)btnLayer(i).TextOn="Layer"&i&"ON"btnLayer(i).TextOff="Layer"&i&"OFF"btnLayer(i).Checked=TruebtnLayer(i).Tag=iEndIfEndSub循环体初始化图层初始化开关按钮ToggleButtons定义了同一

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论