Drawing custom shape onto Canvas in Android

2019-09-08 15:26发布

问题:

I've been stumped by this one for a little bit, so I figured I'd ask here to see if anyone has any pointers.

In a nutshell, I have an app where I want multiple complex shapes to be drawn onto a canvas, which will then be drawn onto the screen (I'll be implementing panning around the large canvas as suggested in this question's answer: Android: Drawing and rotating on a canvas)

How exactly do I go about creating a custom shape and drawing it at arbitrary locations/rotations on a Canvas in Android?

Below is an example of a simple custom shape, as I've tried to implement it so far (typically they'd be created at run-time)

public class Symbol {
    public Bitmap b = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    public Symbol() {
        Canvas canvas = new Canvas(b);;
        Paint paint = new Paint();
        paint.setColor(Color.GRAY);
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(25);
        paint.setStrokeWidth(4);
        paint.setDither(true);                    
        paint.setStrokeJoin(Paint.Join.ROUND);    
        paint.setStrokeCap(Paint.Cap.ROUND);      
        paint.setAntiAlias(true);  
        String str="TestStr";
        canvas.drawText(str, 250,250, paint);
    }
}

回答1:

Wow, I derped hardcore on this one.

Android: canvas.drawBitmap performance issue

Adding this in my main class made everything happy, at least as far as this simple case went.:

Symbol s = new Symbol();
canvas.save();
canvas.rotate(5);
canvas.drawBitmap(s.b, 0,0, null);
canvas.restore();